package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.log.LogCrossTradeWarBattle;
import com.yanqu.road.entity.log.LogTradeWarBattle;
import com.yanqu.road.entity.log.LogTradeWarPrepare;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.servercenter.TitleInfo;
import com.yanqu.road.entity.task.args.union.UnionActivityTaskArgs;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.logic.bussiness.cross.CrossTradeWarBussiness;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.bussiness.player.UserTradeWarBussiness;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.PatronsPb;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.server.gameplayer.module.xiaomian.XiaoMianModule;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.pb.cross.tradewar.CrossTradeWarProto;
import com.yanqu.road.pb.patrons.PatronsProto;
import com.yanqu.road.server.logic.calc.CalculationManager;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.DataAnalyticsMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.TradeWarActivityMgr;
import com.yanqu.road.logic.pb.CrossTradeWarPb;
import com.yanqu.road.server.manger.player.*;
import com.yanqu.road.logic.pb.TradeWarPb;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.decoration.MammonEffectResult;
import com.yanqu.road.entity.config.system.NpcInfo;
import com.yanqu.road.entity.config.battle.BattleResult;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.tradewar.UserTradeWarPatronsData;
import com.yanqu.road.entity.tradewar.*;
import com.yanqu.road.pb.tradewar.TradeWarProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.logic.battle.BattleManager;
import com.yanqu.road.server.logic.player.NpcManager;
import com.yanqu.road.server.manger.config.*;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.pb.TradeWarBattlePb;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ListHelper;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.UUIDHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class TradeWarModule extends GeneralModule {

    public TradeWarModule(GamePlayer player) {
        super(player);
    }

    private UserTradeWarInfo userTradeWarInfo;

    private UserTradeWarBattle userTradeWarBattle;

    private LinkedList<UserTradeWarRecord> recordList;

    private Map<Long, UserTradeWarEnemyRecord> enemyRecordMap = new ConcurrentHashMap<>();

    private long initEnemyRecordTime;

    private long lastTrackTime;    //v5.5新增最后追击时间

    private Map<Integer, UserTradeWarPatronsData> tradeWarPatronsDataMap;

    private CrossUserTradeWarBattle crossUserTradeWarBattle;

    private LinkedList<UserTradeWarRecord> crossTradeWarRecordList;

    private Map<Long, UserTradeWarEnemyRecord> crossEnemyRecordMap = new ConcurrentHashMap<>();

    private long initCrossEnemyRecordTime;

    @Override
    public boolean saveData() {
        if(null != userTradeWarInfo) {
            if (userTradeWarInfo.isInsertOption()) {
                UserTradeWarBussiness.addUserTradeWarInfo(userTradeWarInfo);
            } else if (userTradeWarInfo.isUpdateOption()) {
                UserTradeWarBussiness.updateUserTradeWarInfo(userTradeWarInfo);
            }
        }
        if (null != userTradeWarBattle) {
            if (userTradeWarBattle.isInsertOption()) {
                UserTradeWarBussiness.addUserTradeWarBattle(userTradeWarBattle);
            }else if (userTradeWarBattle.isUpdateOption()) {
                UserTradeWarBussiness.updateUserTradeWarBattle(userTradeWarBattle);
            }
        }

        List<UserTradeWarRecord> tempRecordList = getRecordList();
        if (tempRecordList.size() > 0) {
            for (UserTradeWarRecord record : tempRecordList) {
                if (record.isInsertOption()) {
                    UserTradeWarBussiness.addUserTradeWarRecord(record);
                }else if(record.isUpdateOption()) {
                    UserTradeWarBussiness.updateUserTradeWarRecord(record);
                }
            }
        }

        List<UserTradeWarPatronsData> tempList = new ArrayList<>(tradeWarPatronsDataMap.values());
        for(UserTradeWarPatronsData userTradeWarPatronsData : tempList){
            if(userTradeWarPatronsData.isInsertOption()){
                UserTradeWarBussiness.addUserTradeWarPatronsData(userTradeWarPatronsData);
            }else if(userTradeWarPatronsData.isUpdateOption()){
                UserTradeWarBussiness.updateUserTradeWarPatronsData(userTradeWarPatronsData);
            }
        }

        //跨服商战
        if(null != crossUserTradeWarBattle){
            if(crossUserTradeWarBattle.isInsertOption()){
                CrossTradeWarBussiness.addCrossUserTradeWarBattle(crossUserTradeWarBattle);
            }else if(crossUserTradeWarBattle.isUpdateOption()){
                CrossTradeWarBussiness.updateCrossUserTradeWarBattle(crossUserTradeWarBattle);
            }
        }

        tempRecordList = new ArrayList<>(crossTradeWarRecordList);
        for(UserTradeWarRecord record : tempRecordList){
            if(record.isInsertOption()){
                CrossTradeWarBussiness.addUserTradeWarRecord(record);
            }else if(record.isUpdateOption()){
                CrossTradeWarBussiness.updateUserTradeWarRecord(record);
            }
        }

        return true;
    }

    @Override
    public boolean loadData() {
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        LinkedList<UserTradeWarRecord> tempList = UserTradeWarBussiness.getUserTradeWarRecordList(player.getUserId(), GameConfig.TRADE_WAR_MAX_RECORD);
        LinkedList<UserTradeWarRecord> todayList = UserTradeWarBussiness.getUserTradeWarRecordList(player.getUserId(), zeroTime);
        if(tempList.size() > todayList.size()){
            recordList = tempList;
        }else {
            recordList = todayList;
        }
        initEnemyRecord();

        userTradeWarInfo = UserTradeWarBussiness.getUserTradeWarInfo(player.getUserId());
        if(null != userTradeWarInfo){
            TradeWarMgr.setUserTradeWarInfo(userTradeWarInfo);
        }
        userTradeWarBattle = UserTradeWarBussiness.getUserTradeWarBattle(player.getUserId());
        tradeWarPatronsDataMap = UserTradeWarBussiness.getUserTradeWarPatronsDataMap(player.getUserId());

        //跨服商战
        ActivityInfo openActivity = TradeWarActivityMgr.getOpenActivityInfo();
        if(null != openActivity && TradeWarActivityMgr.canCrossTradeWar(player.getUserId())) {
            LinkedList<UserTradeWarRecord> tempCrossList = CrossTradeWarBussiness.getUserTradeWarRecordList(player.getUserId(),
                    openActivity.getActivityId(), GameConfig.CROSS_TRADE_WAR_MAX_RECORD);
            LinkedList<UserTradeWarRecord> todayCrossList = CrossTradeWarBussiness.getUserTradeWarRecordList(player.getUserId(),
                    openActivity.getActivityId(), zeroTime);
            if(tempCrossList.size() > todayCrossList.size()){
                crossTradeWarRecordList = tempCrossList;
            }else {
                crossTradeWarRecordList = todayCrossList;
            }
            initCrossEnemyRecord();
        }else {
            crossTradeWarRecordList = new LinkedList<>();
        }
        crossUserTradeWarBattle = CrossTradeWarBussiness.getCrossUserTradeWarBattle(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.TradeWar.getValue())) {
            initUserTradeWarInfo();
            initUserTradeWarBattle();
            checkTradeWarPatronsMap();
            calcRandomBattleTimes();
            //跨服商战
            initCrossUserTradeWarBattle();
        }
        return true;
    }

    @Override
    public void afterLogin() {
        player.sendPacket(Protocol.U_TRADE_WAR_WANTED_LIST, TradeWarMgr.getTradeWarWantedListMsg(player));
        checkTradeWarBattle();
        syncUserTradeWarBattle();
        checkTradeWarPatronsMap();
        calcRandomBattleTimes();
        if(null != tradeWarPatronsDataMap){
            syncUserTradeWarPatronsData(new ArrayList<>(tradeWarPatronsDataMap.values()));
        }
        checkRedHotNotify();
        //跨服商战
        syncCrossUserTradeWarBattle();
        syncUserTradeWarInfo();
    }

    @Override
    public void loginSendMsg() {

    }

    /**
     * 商战备战信息异常，检测修复
     */
    private void checkTradeWarBattle(){
        if(null != userTradeWarBattle){
            if(userTradeWarBattle.getEnemyUserId() != 0 && userTradeWarBattle.getPatronsList().size() <= 0){
                long errorEnemyUserId = userTradeWarBattle.getEnemyUserId();
                int errorBuyBuffTimes = userTradeWarBattle.getBuyBuffTimes();
                int errorUseItemId = userTradeWarBattle.getUseItemId();
                int errorBattleType = userTradeWarBattle.getBattleType();
                String errorBattleUid = userTradeWarBattle.getBattleUid();
                clearUserTradeWarBattle();
                log.error("trade war prepare error,userId:{},enemyUserId:{},buyBuffTimes:{},useItemId:{},battleType:{},battleUid:{}",
                        player.getUserId(), errorEnemyUserId, errorBuyBuffTimes, errorUseItemId, errorBattleType, errorBattleUid);
            }
        }
    }

    public void initTradeWarSystem(){
        initUserTradeWarInfo();
        initUserTradeWarBattle();
        syncUserTradeWarBattle();
        checkTradeWarPatronsMap();
        if(null != tradeWarPatronsDataMap){
            syncUserTradeWarPatronsData(new ArrayList<>(tradeWarPatronsDataMap.values()));
        }
        //跨服商战
        initCrossUserTradeWarBattle();
        syncCrossUserTradeWarBattle();
        if(null != tradeWarPatronsDataMap){
            syncCrossUserTradeWarPatronsData(new ArrayList<>(tradeWarPatronsDataMap.values()));
        }
        syncUserTradeWarInfo();
    }

    /**
     * 初始化对手数据
     */
    private void initEnemyRecord() {
        long nowTime = System.currentTimeMillis() / 1000;
        initEnemyRecordTime = nowTime;
        for (UserTradeWarRecord record : recordList) {
            if (TradeWarConfigMgr.isTodayEnemyRecord(nowTime, record)) {
                addEnemyRecord(record);
            }
        }
    }

    /**
     * 初始化跨服对手数据
     */
    private void initCrossEnemyRecord() {
        long nowTime = System.currentTimeMillis() / 1000;
        initCrossEnemyRecordTime = nowTime;
        for (UserTradeWarRecord record : crossTradeWarRecordList) {
            if (TradeWarConfigMgr.isTodayEnemyRecord(nowTime, record)) {
                addCrossEnemyRecord(record, false);
            }
        }
    }

    void resetOneDay(){
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        if(initEnemyRecordTime < zeroTime){
            enemyRecordMap.clear();
            initEnemyRecord();
        }
        if(initCrossEnemyRecordTime < zeroTime){
            crossEnemyRecordMap.clear();
            initCrossEnemyRecord();
        }
        if(null != tradeWarPatronsDataMap){
            List<UserTradeWarPatronsData> syncList = new ArrayList<>();
            int maxRestoreBattleTimes = getMaxRestoreRandomBattleTimes(true);
            int crossMaxRestoreBattleTimes = TradeWarConfigMgr.getMaxCrossRestoreRandomBattleTimes(true);
            for(UserTradeWarPatronsData userTradeWarPatronsData : tradeWarPatronsDataMap.values()){
                if(userTradeWarPatronsData.getModifyTime() < zeroTime){
                    userTradeWarPatronsData.setTotalRandomBattleTimes(0);
                    userTradeWarPatronsData.setRandomBattleRestoreTimes(0);
                    userTradeWarPatronsData.setRandomBattleTimes(maxRestoreBattleTimes);
                    userTradeWarPatronsData.setRestoreRandomBattleTime(zeroTime);
                    userTradeWarPatronsData.setBattleTimes(0);
                    userTradeWarPatronsData.setBuyBattleTimes(0);
                    userTradeWarPatronsData.setCrossTotalRandomBattleTimes(0);
                    userTradeWarPatronsData.setCrossRandomBattleRestoreTimes(0);
                    userTradeWarPatronsData.setCrossRandomBattleTimes(crossMaxRestoreBattleTimes);
                    userTradeWarPatronsData.setCrossRestoreRandomBattleTime(zeroTime);
                    userTradeWarPatronsData.setCrossBattleTimes(0);
                    userTradeWarPatronsData.setCrossBuyBattleTimes(0);
                    userTradeWarPatronsData.setModifyTime(zeroTime);
                    syncList.add(userTradeWarPatronsData);
                }
            }
            if(syncList.size() > 0){
                syncUserTradeWarPatronsData(syncList);
                if(TradeWarActivityMgr.canCrossTradeWar(player.getUserId())) {
                    syncCrossUserTradeWarPatronsData(syncList);
                }
            }
            syncCrossTradeWarEnemyRecord(getCrossTradeWarEnemyRecordList(), true);
        }
        if(null != userTradeWarInfo){
            synchronized (userTradeWarInfo) {
                if (userTradeWarInfo.getDailyTrackResetTime() < zeroTime) {
                    userTradeWarInfo.setDailyTrackTimes(0);
                    userTradeWarInfo.setDailyTrackResetTime(zeroTime);
                    syncUserTradeWarInfo();
                }
            }
        }
    }

    private void initUserTradeWarInfo() {
        if(null == userTradeWarInfo) {
            UserTradeWarInfo tradeWarInfo = new UserTradeWarInfo();
            tradeWarInfo.setUserId(player.getUserId());
            tradeWarInfo.setTotalRandomBattleTimes(0);
            tradeWarInfo.setScore(0);
            tradeWarInfo.setModifyTime(System.currentTimeMillis() / 1000);
            tradeWarInfo.setTotalKillPatronsCount(0L);
            tradeWarInfo.setTotalTradeWarTimes(0L);
            tradeWarInfo.setMaxKillPatronsCount(0);
            tradeWarInfo.setDailyTrackTimes(0);
            tradeWarInfo.setDailyTrackResetTime(LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000);
            tradeWarInfo.setInsertOption();
            userTradeWarInfo = tradeWarInfo;
            TradeWarMgr.setUserTradeWarInfo(userTradeWarInfo);
        }
    }

    private void checkTradeWarPatronsMap(){
        Map<Integer, UserPatrons> patronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
        if (null != patronsMap) {
            for (UserPatrons userPatrons : patronsMap.values()) {
                if (!tradeWarPatronsDataMap.containsKey(userPatrons.getPatronsId())) {
                    initUserTradeWarPatronsData(userPatrons.getPatronsId());
                }
            }
        }
    }

    /**
     * 登录时检测被攻击
     */
    private void checkRedHotNotify(){
        if(userTradeWarInfo == null){
            return;
        }
        long lastNotifyTime = userTradeWarInfo.getLastBeAttackNotifyTime();
        int count = 0;
        for(UserTradeWarRecord userTradeWarRecord : getTopRecordList()){
            if(userTradeWarRecord.getRecordTime() > userTradeWarInfo.getLastBeAttackNotifyTime()){
                count++;
                if(userTradeWarRecord.getRecordTime() > lastNotifyTime){
                    lastNotifyTime = userTradeWarRecord.getRecordTime();
                }
            }
        }
        if(count > 0){
            userTradeWarInfo.setLastBeAttackNotifyTime(lastNotifyTime);
            WorldMessageProto.RedHotNotifyMsg.Builder redHotMsg = WorldMessagePb.parseRedHotNotifyMsg(eRedHotNotifyType.TradeWarBeAttack.getValue(), count, "");
            player.sendPacket(Protocol.U_RED_HOT_NOTIFY, redHotMsg);
        }
    }

    /**
     * 同步用户的商战基本信息
     */
    public void syncUserTradeWarInfo(){
        ActivityInfo openActivityInfo = TradeWarActivityMgr.getOpenActivityInfo();
        if(null != openActivityInfo && null != userTradeWarInfo){
            if(userTradeWarInfo.getActivityId() != openActivityInfo.getActivityId()){
                userTradeWarInfo.setCrossTradeWarMoney(0);
                if(TradeWarActivityMgr.canCrossTradeWar(player.getUserId())){
                    userTradeWarInfo.setActivityId(openActivityInfo.getActivityId());
                }
            }
        }
        TradeWarProto.TradeWarTempMsg.Builder msg = TradeWarPb.parseTradeWarTempMsg(userTradeWarInfo);
        if (null != msg) {
            player.sendPacket(Protocol.U_TRADE_WAR_INFO_SYNC, msg);
        }
    }

    /**
     * 同步商战备战信息
     */
    public void syncUserTradeWarBattle(){
        if (null != userTradeWarBattle) {
            long score = 0;
            if(null != userTradeWarInfo){
                score = userTradeWarInfo.getScore();
            }
            TradeWarProto.TradeWarBattleTempMsg.Builder battleMsg = TradeWarBattlePb.parseTradeWarBattleTempMsg(userTradeWarBattle, score);
            if(null != battleMsg) {
                player.sendPacket(Protocol.U_TRADE_WAR_BATTLE_INFO, battleMsg);
            }
        }
    }

    /**
     * 同步跨服商战备战信息
     */
    public void syncCrossUserTradeWarBattle(){
        if (null != crossUserTradeWarBattle && TradeWarActivityMgr.canCrossTradeWar(player.getUserId())) {
            long score = 0;
            if(null != userTradeWarInfo){
                score = userTradeWarInfo.getCrossScore();
            }
            ActivityInfo openActivityInfo = TradeWarActivityMgr.getOpenActivityInfo();
            if(null != openActivityInfo){
                if(crossUserTradeWarBattle.getActivityId() != openActivityInfo.getActivityId()){
                    clearCrossTradeWarBattle();
                    crossUserTradeWarBattle.setActivityId(openActivityInfo.getActivityId());
                }
            }
            CrossTradeWarProto.CrossTradeWarBattleTempMsg.Builder crossBattleMsg = CrossTradeWarPb.parseCrossTradeWarBattleTempMsg(crossUserTradeWarBattle, score);
            if(null != crossBattleMsg) {
                player.sendPacket(Protocol.U_CROSS_TRADE_WAR_BATTLE_INFO, crossBattleMsg);
            }
            if(null != tradeWarPatronsDataMap){
                calcCrossRandomBattleTimes();
                syncCrossUserTradeWarPatronsData(new ArrayList<>(tradeWarPatronsDataMap.values()));
            }
            checkCrossRecord(openActivityInfo.getActivityId());
            List<UserTradeWarRecord> recordList = new ArrayList<>(crossTradeWarRecordList);
            if(recordList.size() > GameConfig.CROSS_TRADE_WAR_MAX_RECORD){
                recordList.subList(recordList.size() - GameConfig.CROSS_TRADE_WAR_MAX_RECORD, recordList.size());
            }
            syncCrossTradeRecord(crossTradeWarRecordList, true);
            syncCrossTradeWarEnemyRecord(getCrossTradeWarEnemyRecordList(), true);
            sendCrossGetWantedList(openActivityInfo.getActivityId());
        }
    }

    /**
     * 检测过期活动的记录
     * @param activityId
     */
    private void checkCrossRecord(int activityId){
        synchronized (crossTradeWarRecordList){
            int length = crossTradeWarRecordList.size();
            for(int i = length -1; i >= 0; i--){
                UserTradeWarRecord record = crossTradeWarRecordList.get(i);
                if(record.getActivityId() != activityId){
                    crossTradeWarRecordList.remove(record);
                }
            }
        }
    }

    /**
     *同步商战中门客的信息
     */
    private void syncUserTradeWarPatronsData(List<UserTradeWarPatronsData> userTradeWarPatronsDataList){
        player.sendPacket(Protocol.U_TRADE_WAR_PATRONS_DATA_SYNC, TradeWarPb.parseTradeWarPatronsDataListMsg(userTradeWarPatronsDataList));
    }

    /**
     *同步商战中门客的信息
     */
    private void syncUserTradeWarPatronsData(UserTradeWarPatronsData userTradeWarPatronsData){
        if(null != userTradeWarPatronsData){
            List<UserTradeWarPatronsData> syncList = new ArrayList<>();
            syncList.add(userTradeWarPatronsData);
            syncUserTradeWarPatronsData(syncList);
        }
    }

    /**
     *同步商战中门客的信息
     */
    private void syncCrossUserTradeWarPatronsData(List<UserTradeWarPatronsData> userTradeWarPatronsDataList){
        player.sendPacket(Protocol.U_CROSS_TRADE_WAR_PATRONS_DATA_SYNC, CrossTradeWarPb.parseTradeWarPatronsDataListMsg(userTradeWarPatronsDataList));
    }

    /**
     *同步商战中门客的信息
     */
    private void syncCrossUserTradeWarPatronsData(UserTradeWarPatronsData userTradeWarPatronsData){
        if(null != userTradeWarPatronsData){
            List<UserTradeWarPatronsData> syncList = new ArrayList<>();
            syncList.add(userTradeWarPatronsData);
            syncCrossUserTradeWarPatronsData(syncList);
        }
    }

    /**
     * 初始化商战备战信息
     */
    private void initUserTradeWarBattle() {
        if (null == userTradeWarBattle) {
            userTradeWarBattle = new UserTradeWarBattle();
            userTradeWarBattle.setUserId(player.getUserId());
            clearUserTradeWarBattle();
            userTradeWarBattle.setInsertOption();
        }else if(userTradeWarBattle.getWarTimes() == 0){
            userTradeWarBattle.setWarTimes(1);   //旧数据补偿
        }
    }

    /**
     * 初始化跨服商战备战信息
     */
    private void initCrossUserTradeWarBattle() {
        if (null == crossUserTradeWarBattle) {
            crossUserTradeWarBattle = new CrossUserTradeWarBattle();
            crossUserTradeWarBattle.setUserId(player.getUserId());
            ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
            if(null != activityInfo){
                crossUserTradeWarBattle.setActivityId(activityInfo.getActivityId());
            }
            clearCrossTradeWarBattle();
            crossUserTradeWarBattle.setInsertOption();
        }
    }

    /**
     * 获取商战中的门客信息
     */
    public UserTradeWarPatronsData getUserTradeWarPatronsData(int patronsId){
        initUserTradeWarPatronsData(patronsId);
        return tradeWarPatronsDataMap.get(patronsId);
    }

    /**
     * 初始化商战中的门客信息
     */
    private void initUserTradeWarPatronsData(int patronsId) {
        if(!tradeWarPatronsDataMap.containsKey(patronsId) && player.getModule(PatronsModule.class).getUserPatronsMap().containsKey(patronsId)){
            long nowTime = System.currentTimeMillis() / 1000;
            UserTradeWarPatronsData userTradeWarPatronsData = new UserTradeWarPatronsData();
            userTradeWarPatronsData.setUserId(player.getUserId());
            userTradeWarPatronsData.setPatronsId(patronsId);
            userTradeWarPatronsData.setBattleTimes(0);
            userTradeWarPatronsData.setBuyBattleTimes(0);
            userTradeWarPatronsData.setRandomBattleTimes(getMaxRestoreRandomBattleTimes(true));
            userTradeWarPatronsData.setTotalRandomBattleTimes(0);
            userTradeWarPatronsData.setRandomBattleRestoreTimes(0);
            userTradeWarPatronsData.setRestoreRandomBattleTime(nowTime);
            userTradeWarPatronsData.setModifyTime(nowTime);
            //跨服出战
            userTradeWarPatronsData.setCrossBattleTimes(0);
            userTradeWarPatronsData.setCrossBuyBattleTimes(0);
            userTradeWarPatronsData.setCrossRandomBattleTimes(TradeWarConfigMgr.getMaxCrossRestoreRandomBattleTimes(true));
            userTradeWarPatronsData.setCrossTotalRandomBattleTimes(0);
            userTradeWarPatronsData.setCrossRandomBattleRestoreTimes(0);
            userTradeWarPatronsData.setCrossRestoreRandomBattleTime(nowTime);
            userTradeWarPatronsData.setInsertOption();
            tradeWarPatronsDataMap.put(userTradeWarPatronsData.getPatronsId(), userTradeWarPatronsData);
        }
    }

    /**
     * 清除商战备战信息
     */
    private void clearUserTradeWarBattle() {
        if (null != userTradeWarBattle) {
            userTradeWarBattle.setBattleType(0);
            userTradeWarBattle.setBuyBuffTimes(0);
            userTradeWarBattle.setPatronsList(new ArrayList<>());
            userTradeWarBattle.setEnemyUserId(0);
            userTradeWarBattle.setEnemyNickName("");
            userTradeWarBattle.setEnemyTitleId(0);
            userTradeWarBattle.setEnemyDecoration("");
            userTradeWarBattle.setEnemyCity("");
            userTradeWarBattle.setEnemyScore(0);
            userTradeWarBattle.setEnemyVipExp(0);
            userTradeWarBattle.setEnemyPatronsCount(0);
            userTradeWarBattle.setUseItemId(0);
            userTradeWarBattle.setBattleUid("");
            userTradeWarBattle.setModifyTime(System.currentTimeMillis() / 1000);
            userTradeWarBattle.setWarTimes(1);
        }
    }

    /**
     * 清除跨服商战备战信息
     */
    public void clearCrossTradeWarBattle() {
        if (null != crossUserTradeWarBattle) {
            crossUserTradeWarBattle.setBattleType(0);
            crossUserTradeWarBattle.setBuyBuffTimes(0);
            crossUserTradeWarBattle.setPatronsList(new ArrayList<>());
            crossUserTradeWarBattle.setEnemyUserId(0);
            crossUserTradeWarBattle.setEnemyBaseInfo(new UserBaseInfo());
            crossUserTradeWarBattle.setEnemyScore(0);
            crossUserTradeWarBattle.setEnemyPatronsCount(0);
            crossUserTradeWarBattle.setUseItemId(0);
            crossUserTradeWarBattle.setBattleUid("");
            crossUserTradeWarBattle.setFastTeamNum(-1);
            crossUserTradeWarBattle.setModifyTime(System.currentTimeMillis() / 1000);
        }
    }

    public UserTradeWarBattle getUserTradeWarBattle() {
        return userTradeWarBattle;
    }

    /**
     * 商战备战
     * @param battleType 商战类型，随机出战、挑战、通缉
     * @param patronsIdList 出战门客
     * @param enemyUserId 对手
     * @param battleUid 挑战记录唯一标识，反击或者追辑才有
     * @param useItemId 使用挑战道具
     * @param warTimes 出战次数
     * @return 结果值
     */
    public int prepare(int battleType, List<Integer> patronsIdList, long enemyUserId, String battleUid, int useItemId, int warTimes) {
        int ret;
        if(null == userTradeWarInfo){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if(null == userTradeWarBattle){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        //计算一下随机战斗次数
        calcRandomBattleTimes();
        if(userTradeWarBattle.getEnemyUserId() != 0){
            return GameErrorCode.E_TRADE_WAR_HAS_PREPARE;
        }

        if(eTradeWarBattleType.RandomBattle.getValue() == battleType){//随机出战
            return randomBattle(patronsIdList, warTimes);
        }else {
            //对手信息
            UserTradeWarInfo enemyTradeWarInfo = TradeWarMgr.getUserTradeWarInfo(enemyUserId);
            UserInfo enemyUserInfo = UserMgr.getUserInfo(enemyUserId);
            if(null == enemyTradeWarInfo || null == enemyUserInfo){
                return GameErrorCode.E_TRADE_WAR_BATTLE_ENEMY_NO_FOUND;
            }
            if(enemyUserId == player.getUserId()){
                return GameErrorCode.E_TRADE_WAR_BATTLE_ENEMY_NO_SELF;
            }

            //判断门客的挑战次数
            CheckPatronsBattleResult checkResult = null;
            if(eTradeWarBattleType.Track.getValue() != battleType) {//3.6修改追缉不消耗挑战次数
                //判断门客的挑战次数
                checkResult = checkBattleTimes(patronsIdList, false);
                if (0 != checkResult.getRet()) {
                    return checkResult.getRet();
                }
            }

            Property consume = new Property();
            if(eTradeWarBattleType.Challenge.getValue() == battleType || eTradeWarBattleType.FightBack.getValue() == battleType){//挑战或者反击
                if(!GoodsMgr.isTradeWarChallenge(useItemId)){
                    return GameErrorCode.E_BAG_GOODS_NO_TRADE_WAR_CHALLENGE;
                }
                if(eTradeWarBattleType.FightBack.getValue() == battleType){
                    UserTradeWarEnemyRecord userTradeWarSimpleRecord = enemyRecordMap.get(enemyUserId);
                    if(null == userTradeWarSimpleRecord){
                        return GameErrorCode.E_TRADE_WAR_NO_ATTACK_CANNOT_FIGHT_BACK;
                    }
                    if(userTradeWarSimpleRecord.getFightBackTimes() >= userTradeWarSimpleRecord.getTotalFightTimes()){
                        return GameErrorCode.E_TRADE_WAR_ALREADY_FIGHT_BACK;
                    }
                    UserTradeWarRecord tradeWarRecord = getCanFightBackTradeWarRecord(enemyUserId);
                    if(null == tradeWarRecord){
                        return GameErrorCode.E_TRADE_WAR_NO_ATTACK_CANNOT_FIGHT_BACK;
                    }
                    if(tradeWarRecord.isBattle()){
                        return GameErrorCode.E_TRADE_WAR_ALREADY_FIGHT_BACK;
                    }
                    if(!player.getModule(CurrencyModule.class).removeCurrency(new Property(useItemId, BigInteger.ONE),
                            eLogMoneyType.TradeWar, eLogMoneyType.TradeWarBattle)){//判断挑战道具是否足够
                        return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                    }
                    tradeWarRecord.setBattle(true);
                    userTradeWarSimpleRecord.setFightBackTimes(userTradeWarSimpleRecord.getFightBackTimes() + 1);
                }else if(eTradeWarBattleType.Challenge.getValue() == battleType){
                    if(!TradeWarMgr.isInNoticeList(enemyUserId)){
                        return GameErrorCode.E_TRADE_WAR_NO_IN_NOTICE_CANNOT_CHALLENGE;
                    }
                    consume.addProperty(useItemId, BigInteger.ONE);
                    if(!player.getModule(CurrencyModule.class).removeCurrency(new Property(useItemId, BigInteger.ONE),
                            eLogMoneyType.TradeWar, eLogMoneyType.TradeWarBattle)){//判断挑战道具是否足够
                        //挑战，触发现金礼包
                        player.notifyListener(eGamePlayerEventType.RechargeTradeWarChallenge.getValue(), 0);
                        return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                    }
                }
            }else if(eTradeWarBattleType.Track.getValue() == battleType){//追辑
                long nowTime = System.currentTimeMillis();
                if ((nowTime - lastTrackTime) < GameConfig.TRADE_WAR_WANTED_CD * 1000) {
                    return GameErrorCode.E_TRADE_WAR_TRACK_TOO_FAST;
                }
                ret = TradeWarMgr.trackPrepare(player, battleUid);
                if(0 != ret){
                    return ret;
                }
                lastTrackTime = nowTime;   //5.5新增追击时间限制外挂
                userTradeWarBattle.setBattleUid(battleUid);
            }else {
                return GameErrorCode.E_TRADE_WAR_BATTLE_TYPE_ERROR;
            }
            //消耗次数
            if(eTradeWarBattleType.Track.getValue() != battleType) {//3.6修改追缉不消耗挑战次数
                checkResult = checkBattleTimes(patronsIdList, true);
                if (0 != checkResult.getRet()) {
                    return checkResult.getRet();
                }
            }
            userTradeWarBattle.setBattleType(battleType);
            setPatronsList(patronsIdList);
            userTradeWarBattle.setUseItemId(useItemId);
            setBattleEnemyInfo(enemyUserId, enemyUserInfo.getNickName(), enemyUserInfo.getTitleId(), UserMgr.getDecoration(enemyUserId),
                    enemyTradeWarInfo.getScore(), enemyUserInfo.getVipExp(), enemyUserInfo.getPatronsCount(), enemyUserInfo.getCity());
            if(null != checkResult) {
                consume.addProperty(checkResult.getConsume());
            }
            AutoLogMgr.add(new LogTradeWarPrepare(player.getUserId(), battleType, enemyUserId, StringUtils.listToString(patronsIdList, ","),
                    PropertyHelper.parsePropertyToString(consume), false));
            return 0;
        }
    }

    /**
     *随机出战
     */
    private int randomBattle(List<Integer> patronsIdList, int warTimes){
        if(!hasRandomBattleTimes(patronsIdList, warTimes)){//没有随机出使次数了
            return GameErrorCode.E_TRADE_WAR_RANDOM_BATTLE_TIMES_OVER;
        }
        userTradeWarBattle.setWarTimes(warTimes);
        userTradeWarBattle.setBattleType(eTradeWarBattleType.RandomBattle.getValue());
        setPatronsList(patronsIdList);
        //获取随机对手
        UserTradeWarInfo enemyTradeWarInfo = null;
        if(userTradeWarInfo.getTotalRandomBattleTimes() > GameConfig.TRADE_WAR_BATTLE_NPC_TIMES){//从玩家池中随机一个对手
            enemyTradeWarInfo = TradeWarMgr.findRandomEnemy(player.getUserId());
        }

        //扣除出使次数
        reduceRandomBattleTimes(patronsIdList, warTimes);

        userTradeWarInfo.setTotalRandomBattleTimes(userTradeWarInfo.getTotalRandomBattleTimes() + userTradeWarBattle.getWarTimes());
        if(null == enemyTradeWarInfo){//机器人上场
            NpcInfo npcInfo = NpcManager.getRandomNpc(player.getLanguage());
            int enemyPatronsCount = player.getModule(PatronsModule.class).getUserPatronsMap().size();
            if(enemyPatronsCount >= GameConfig.TRADE_WAR_NOTICE_NEED_KILL_PATRONS_COUNT){
                enemyPatronsCount = GameConfig.TRADE_WAR_NOTICE_NEED_KILL_PATRONS_COUNT - 1;
            }
            setBattleEnemyInfo(-1, npcInfo.getNickName(), npcInfo.getTitleId(), npcInfo.getDecoration(), 0, npcInfo.getVipExp(),
                    enemyPatronsCount, npcInfo.getCity());
        }else {
            UserInfo enemyUserInfo = UserMgr.getUserInfo(enemyTradeWarInfo.getUserId());
            int enemyPatronsCount;
            GamePlayer enemyPlayer = GamePlayerMgr.getOnlinePlayer(enemyTradeWarInfo.getUserId());
            if(null != enemyPlayer){
                enemyPatronsCount = enemyPlayer.getModule(PatronsModule.class).getUserPatronsMap().size();
            }else {
                enemyPatronsCount = enemyUserInfo.getPatronsCount();
            }
            setBattleEnemyInfo(enemyTradeWarInfo.getUserId(), enemyUserInfo.getNickName(), enemyUserInfo.getTitleId(), UserMgr.getDecoration(enemyUserInfo.getUserId()),
                    enemyTradeWarInfo.getScore(), enemyUserInfo.getVipExp(), enemyPatronsCount, enemyUserInfo.getCity());
        }
        AutoLogMgr.add(new LogTradeWarPrepare(player.getUserId(), eTradeWarBattleType.RandomBattle.getValue(), userTradeWarBattle.getEnemyUserId(),
                StringUtils.listToString(patronsIdList, ","), "", false));
        return 0;
    }

    public int crossPrepare(int activityId, int battleType, List<Integer> patronsIdList, long enemyUserId, long enemyServerId, String battleUid, int useItemId) {
        if(null == userTradeWarInfo){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if(null == crossUserTradeWarBattle){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if(null == activityInfo){
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if(crossUserTradeWarBattle.getActivityId() != activityId){
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_QUALIFIED;
        }
        if(!ActivityMgr.activityInTime(activityInfo)){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        //计算一下跨服随机战斗次数
        calcCrossRandomBattleTimes();
        if(crossUserTradeWarBattle.getEnemyUserId() != 0){
            return GameErrorCode.E_TRADE_WAR_HAS_PREPARE;
        }
        if (enemyUserId > 0 && enemyUserId == player.getUserId() && enemyServerId == GameServer.getInstance().getServerId()) {
            return GameErrorCode.E_TRADE_WAR_BATTLE_ENEMY_NO_SELF;
        }
        if (eTradeWarBattleType.RandomBattle.getValue() == battleType) {//随机出战
            return crossRandomBattle(activityInfo, battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        } else if (eTradeWarBattleType.Challenge.getValue() == battleType) {//挑战
            return crossChallenge(activityInfo, battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        } else if (eTradeWarBattleType.FightBack.getValue() == battleType) {//反击
            return crossFightBack(activityInfo, battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        } else if (eTradeWarBattleType.Track.getValue() == battleType) {//追缉
            return crossTrack(activityInfo, battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        } else {
            return GameErrorCode.E_TRADE_WAR_BATTLE_TYPE_ERROR;
        }
    }

    public int crossFastRandomBattle(int activityId, int teamNum) {
        if (null == userTradeWarInfo) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if (null == crossUserTradeWarBattle) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if (null == activityInfo) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if (crossUserTradeWarBattle.getActivityId() != activityId) {
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_QUALIFIED;
        }
        if (!ActivityMgr.activityInTime(activityInfo)) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        int ret = player.getModule(TradeWarTeamModule.class).titleOrVipCheck(1);
        if (ret != 0) {
            return ret;
        }
        //计算一下跨服随机战斗次数
        calcCrossRandomBattleTimes();
        if (crossUserTradeWarBattle.getEnemyUserId() != 0) {
            return GameErrorCode.E_TRADE_WAR_HAS_PREPARE;
        }
        UserCrossTradeWarTeam userCrossTradeWarTeam = player.getModule(TradeWarTeamModule.class).getUserCrossTradeWarTeam();
        if (userCrossTradeWarTeam == null) {
            return GameErrorCode.E_TRADE_WAR_RANDOM_BATTLE_TIMES_OVER;
        }
        List<Integer> patronsIdList = userCrossTradeWarTeam.getPatronsIdList(teamNum);
        List<Integer> realPatronsIdList = new ArrayList<>();
        //取一下有出战次数的
        for (Integer patronsId : patronsIdList) {
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                continue;
            }
            if(patronsData.getCrossRandomBattleTimes() < 1){
                continue;
            }
            realPatronsIdList.add(patronsId);
        }

        return crossFastRandomBattle(activityInfo, realPatronsIdList, teamNum);
    }

    /**
     * 跨服商战本地匹配完成发送信息
     */
    private void sendLocalPrepareFinish() {
        CrossTradeWarProto.CrossTradeWarBattleRespMsg.Builder respMsg = CrossTradeWarProto.CrossTradeWarBattleRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossTradeWarProto.CrossTradeWarBattleTempMsg.Builder msg = CrossTradeWarPb.parseCrossTradeWarBattleTempMsg(crossUserTradeWarBattle, userTradeWarInfo.getCrossScore());
        respMsg.setBattleInfo(msg);
        if (crossUserTradeWarBattle.getEnemyUserId() > 0) {
            Map<Integer, UserPatrons> enemyPatronsMap;
            GamePlayer enemyPlayer = GamePlayerMgr.getOnlinePlayer(crossUserTradeWarBattle.getEnemyUserId());
            if (null != enemyPlayer) {
                enemyPatronsMap = enemyPlayer.getModule(PatronsModule.class).getUserPatronsMap();
            } else {
                enemyPatronsMap = UserPatronsBussiness.getUserPatronsMap(crossUserTradeWarBattle.getEnemyUserId());
            }
            for (UserPatrons userPatrons : enemyPatronsMap.values()) {
                PatronsProto.PatronsTempMsg.Builder patronsMsg = PatronsPb.parsePatronsTempMsg(userPatrons);
                if (null != patronsMsg) {
                    respMsg.addEnemyPatronsList(patronsMsg);
                }
            }
            respMsg.setEnemyPatronsAbility(PatronsMgr.getPatronsListAbility(new ArrayList<>(enemyPatronsMap.values())).toString());
        }
        player.sendPacket(Protocol.U_CROSS_TRADE_WAR_BATTLE_PREPARE, respMsg);
    }

    /**
     * 跨服匹配完成通知
     */
    public int crossPrepareNotify(int activityId, int battleType, List<Integer> patronsIdList, int useItemId, long enemyUserId, long enemyScore,
                                  int enemyPatronsCount, String battleUid, UserBaseInfo enemyBaseInfo, int wantedItemId, long publishWantedUserId, int teamNum) {
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if (null == activityInfo) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if (crossUserTradeWarBattle.getActivityId() != activityId) {
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_FOUND_BATTLE_FAIL;
        }
        if (crossUserTradeWarBattle.getBattleType() != battleType) {
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_REPEAT_PREPARE;
        }
        if(!ListHelper.integerListCompare(crossUserTradeWarBattle.getPatronsList(), patronsIdList)){
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_REPEAT_PREPARE;
        }
        if(eTradeWarBattleType.RandomBattle.getValue() == battleType) {//随机出战
            if (crossUserTradeWarBattle.getEnemyUserId() != 0) {
                return GameErrorCode.E_TRADE_WAR_HAS_PREPARE;
            }
            crossUserTradeWarBattle.setFastTeamNum(teamNum);
            if (teamNum >= 0) {
                //取队伍里的鼓舞购买次数
                int buffTimes = player.getModule(TradeWarTeamModule.class).calcCrossTradeWarBuffTimes(teamNum);
                crossUserTradeWarBattle.setBuyBuffTimes(buffTimes);
            }
            //扣除出使次数
            reduceCrossRandomBattleTimes(patronsIdList);
            userTradeWarInfo.setTotalRandomBattleTimes(userTradeWarInfo.getTotalRandomBattleTimes() + 1);
            setCrossBattleEnemyInfo(enemyUserId, enemyScore, enemyPatronsCount, enemyBaseInfo, battleUid);
            AutoLogMgr.add(new LogTradeWarPrepare(player.getUserId(), eTradeWarBattleType.RandomBattle.getValue(), crossUserTradeWarBattle.getEnemyUserId(),
                    StringUtils.listToString(patronsIdList, ","), "", true));

        }else {
            //判断门客的挑战次数
            CheckPatronsBattleResult checkResult;
            if(eTradeWarBattleType.Track.getValue() != battleType) {//3.6修改追缉不消耗挑战次数
                checkResult = checkCrossBattleTimes(patronsIdList, false);
                if (0 != checkResult.getRet()) {
                    return checkResult.getRet();
                }
            }
            Property consume = new Property();
            if(eTradeWarBattleType.Challenge.getValue() == battleType || eTradeWarBattleType.FightBack.getValue() == battleType) {
                if (!GoodsMgr.isTradeWarChallenge(useItemId)) {
                    return GameErrorCode.E_BAG_GOODS_NO_TRADE_WAR_CHALLENGE;
                }
                consume.addProperty(useItemId, BigInteger.ONE);
                if (eTradeWarBattleType.FightBack.getValue() == battleType) {
                    if(crossUserTradeWarBattle.getEnemyUserId() != 0){
                        return GameErrorCode.E_TRADE_WAR_HAS_PREPARE;
                    }
                    UserTradeWarEnemyRecord userTradeWarSimpleRecord = crossEnemyRecordMap.get(enemyUserId);
                    if (null == userTradeWarSimpleRecord) {
                        return GameErrorCode.E_TRADE_WAR_NO_ATTACK_CANNOT_FIGHT_BACK;
                    }
                    if (userTradeWarSimpleRecord.getFightBackTimes() >= userTradeWarSimpleRecord.getTotalFightTimes()) {
                        return GameErrorCode.E_TRADE_WAR_ALREADY_FIGHT_BACK;
                    }
                    UserTradeWarRecord tradeWarRecord = getCanFightBackCrossTradeWarRecord(enemyUserId);
                    if (null == tradeWarRecord) {
                        return GameErrorCode.E_TRADE_WAR_NO_ATTACK_CANNOT_FIGHT_BACK;
                    }
                    if (tradeWarRecord.isBattle()) {
                        return GameErrorCode.E_TRADE_WAR_ALREADY_FIGHT_BACK;
                    }
                    if (!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.TradeWar,
                            eLogMoneyType.CrossTradeWarFightBackCost)) {//判断挑战道具是否足够
                        return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                    }
                    tradeWarRecord.setBattle(true);
                    userTradeWarSimpleRecord.setFightBackTimes(userTradeWarSimpleRecord.getFightBackTimes() + 1);
                    syncCrossTradeWarEnemyRecord(userTradeWarSimpleRecord);
                } else {
                    if(crossUserTradeWarBattle.getEnemyUserId() != 0){
                        return GameErrorCode.E_TRADE_WAR_HAS_PREPARE;
                    }
                    if (!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.TradeWar,
                            eLogMoneyType.CrossTradeWarChallengeCost)) {//判断挑战道具是否足够
                        return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                    }
                }
            }else if(eTradeWarBattleType.Track.getValue() == battleType){//追缉
                if(player.getUserId() != publishWantedUserId) {//不是自己发布的通缉
                    GoodsInfo goodsInfo = GoodsMgr.getGoodsById(wantedItemId);
                    int addTimes = 1;
                    if(null != goodsInfo){
                        addTimes = goodsInfo.getParamList().get(0).intValue();
                    }
                    if (userTradeWarInfo.getDailyTrackTimes() + addTimes > ConfigMgr.getTradeWarTrackTimesByVip(VipMgr.getVipLv(player.getUserInfo().getVipExp()))) {
                        return GameErrorCode.E_TRADE_WAR_TRACK_TIMES_OVER;
                    }
                    addTraceTimes(addTimes);            //加追缉次数
                }
            }else {
                return GameErrorCode.E_TRADE_WAR_BATTLE_TYPE_ERROR;
            }
            //消耗次数
            if(eTradeWarBattleType.Track.getValue() != battleType) {//3.6修改追缉不消耗挑战次数
                checkResult = checkCrossBattleTimes(patronsIdList, true);
                if (0 != checkResult.getRet()) {
                    return checkResult.getRet();
                }
            }
            crossUserTradeWarBattle.setUseItemId(useItemId);
            setCrossBattleEnemyInfo(enemyUserId, enemyScore, enemyPatronsCount, enemyBaseInfo, battleUid);
            AutoLogMgr.add(new LogTradeWarPrepare(player.getUserId(), battleType, enemyUserId, StringUtils.listToString(patronsIdList, ","),
                    PropertyHelper.parsePropertyToString(consume), true));
            return 0;
        }
        return 0;
    }

    private void setCrossBattleEnemyInfo(long enemyUserId, long enemyScore, int enemyPatronsCount, UserBaseInfo enemyBaseInfo, String battleUid) {
        crossUserTradeWarBattle.setEnemyUserId(enemyUserId);
        crossUserTradeWarBattle.setEnemyScore(enemyScore);
        crossUserTradeWarBattle.setEnemyPatronsCount(enemyPatronsCount);
        crossUserTradeWarBattle.setEnemyBaseInfo(enemyBaseInfo);
        crossUserTradeWarBattle.setBattleUid(battleUid);
    }

    /**
     *跨服随机出战
     */
    private int crossRandomBattle(ActivityInfo activityInfo, int battleType, List<Integer> patronsIdList, long enemyUserId, long enemyServerId,
                                  String battleUid, int useItemId){
        if(!hasCrossRandomBattleTimes(patronsIdList)){//没有随机出使次数了
            return GameErrorCode.E_TRADE_WAR_RANDOM_BATTLE_TIMES_OVER;
        }
        long randomServer = TradeWarActivityMgr.getRandomServerId(activityInfo,getUserId());
        if(randomServer == GameServer.getInstance().getServerId()){//匹配自己区服的对手
            UserTradeWarInfo enemyTradeWarInfo = TradeWarMgr.findCrossRandomEnemy(activityInfo.getActivityId(), player.getUserId(), GameServer.getInstance().getServerId());
            if(null == enemyTradeWarInfo){//本服找不到对手，到跨服找
                //需要到跨服匹配
                return sendCrossPrepare(activityInfo.getActivityId(), battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
            }else {
                UserInfo enemyUserInfo = UserMgr.getUserInfo(enemyTradeWarInfo.getUserId());
                crossUserTradeWarBattle.setBattleType(battleType);
                setCrossPatronsList(patronsIdList);
                int ret = crossPrepareNotify(activityInfo.getActivityId(), battleType, patronsIdList, useItemId, enemyTradeWarInfo.getUserId(), enemyTradeWarInfo.getCrossScore(),
                        enemyUserInfo.getPatronsCount(), battleUid, UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()), 0, 0, -1);
                if (0 != ret) {
                    return ret;
                } else {//本地匹配完成，发送消息
                    sendLocalPrepareFinish();
                    return 0;
                }
            }
        } else {//需要到跨服匹配
            return sendCrossPrepare(activityInfo.getActivityId(), battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        }
    }

    /**
     * 跨服随机出战
     */
    private int crossFastRandomBattle(ActivityInfo activityInfo, List<Integer> patronsIdList, int teamNum) {
        int battleType = eTradeWarBattleType.RandomBattle.getValue();
        long enemyUserId = 0l;
        long enemyServerId = 0l;
        int useItemId = 0;
        String battleUid = "";
        if (!hasCrossRandomBattleTimes(patronsIdList)) {//没有随机出使次数了
            return GameErrorCode.E_TRADE_WAR_RANDOM_BATTLE_TIMES_OVER;
        }
        long randomServer = TradeWarActivityMgr.getRandomServerId(activityInfo, getUserId());
        if (randomServer == GameServer.getInstance().getServerId()) {//匹配自己区服的对手
            UserTradeWarInfo enemyTradeWarInfo = TradeWarMgr.findCrossRandomEnemy(activityInfo.getActivityId(), player.getUserId(), GameServer.getInstance().getServerId());
            if (null == enemyTradeWarInfo) {//本服找不到对手，到跨服找
                //需要到跨服匹配
                return sendCrossFastPrepare(activityInfo.getActivityId(), battleType, patronsIdList, teamNum);
            } else {
                UserInfo enemyUserInfo = UserMgr.getUserInfo(enemyTradeWarInfo.getUserId());
                crossUserTradeWarBattle.setBattleType(battleType);
                setCrossPatronsList(patronsIdList);
                int ret = crossPrepareNotify(activityInfo.getActivityId(), battleType, patronsIdList, useItemId, enemyTradeWarInfo.getUserId(), enemyTradeWarInfo.getCrossScore(),
                        enemyUserInfo.getPatronsCount(), battleUid, UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()), 0, 0, teamNum);
                if (0 != ret) {
                    return ret;
                } else {//本地匹配完成，发送消息
                    //开始战斗
                    player.sendPacket(Protocol.S_CROSS_TRADE_WAR_BATTLE_START, CrossTradeWarProto.CrossTradeWarBattleStartReqMsg.newBuilder().setActivityId(activityInfo.getActivityId()));
                    return 0;
                }
            }
        } else {//需要到跨服匹配
            return sendCrossFastPrepare(activityInfo.getActivityId(), battleType, patronsIdList, teamNum);
        }
    }

    /**
     * 跨服挑战
     */
    private int crossChallenge(ActivityInfo activityInfo, int battleType, List<Integer> patronsIdList, long enemyUserId, long enemyServerId,
                               String battleUid, int useItemId) {
        if (enemyServerId == GameServer.getInstance().getServerId()) {//挑战本服
            if (!TradeWarActivityMgr.canCrossTradeWar(activityInfo.getActivityId(), enemyUserId)) {
                return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_CAN_NO_BATTLE;
            }
            UserTradeWarInfo enemyTradeWarInfo = TradeWarMgr.getUserTradeWarInfo(enemyUserId);
            UserInfo enemyUserInfo = UserMgr.getUserInfo(enemyUserId);
            if (null == enemyTradeWarInfo || null == enemyUserInfo) {
                return GameErrorCode.E_TRADE_WAR_BATTLE_ENEMY_NO_FOUND;
            }
            if (enemyUserId == player.getUserId()) {
                return GameErrorCode.E_TRADE_WAR_BATTLE_ENEMY_NO_SELF;
            }
            //判断门客的挑战次数
            CheckPatronsBattleResult checkResult = checkCrossBattleTimes(patronsIdList, false);
            if (0 != checkResult.getRet()) {
                return checkResult.getRet();
            }

            if (!GoodsMgr.isTradeWarChallenge(useItemId)) {
                return GameErrorCode.E_BAG_GOODS_NO_TRADE_WAR_CHALLENGE;
            }
            Property consume = new Property();
            consume.addProperty(useItemId, BigInteger.ONE);
            if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(useItemId, BigInteger.ONE),
                    eLogMoneyType.TradeWar, eLogMoneyType.CrossTradeWarChallenge)) {//判断挑战道具是否足够
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }

            //消耗次数
            checkResult = checkCrossBattleTimes(patronsIdList, true);
            if (0 != checkResult.getRet()) {
                return checkResult.getRet();
            }
            crossUserTradeWarBattle.setBattleType(battleType);
            setCrossPatronsList(patronsIdList);
            crossUserTradeWarBattle.setUseItemId(useItemId);
            setCrossBattleEnemyInfo(enemyUserId, enemyTradeWarInfo.getScore(), enemyUserInfo.getPatronsCount(),
                    UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()), battleUid);
            AutoLogMgr.add(new LogTradeWarPrepare(player.getUserId(), battleType, enemyUserId, StringUtils.listToString(patronsIdList, ","),
                    PropertyHelper.parsePropertyToString(consume), true));
            //本地匹配完成，发送消息
            sendLocalPrepareFinish();
            return 0;
        }else {//挑战跨服
            if(!ServerListMgr.isServerProvideServices(enemyServerId)){//对手区服停服
                return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_SERVER_MAINTAIN;
            }
            //判断门客的挑战次数
            CheckPatronsBattleResult checkResult = checkCrossBattleTimes(patronsIdList, false);
            if (0 != checkResult.getRet()) {
                return checkResult.getRet();
            }
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(new Property(useItemId, BigInteger.ONE))) {//判断挑战道具是否足够
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            return sendCrossPrepare(activityInfo.getActivityId(), battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        }
    }

    /**
     * 跨服反击
     */
    private int crossFightBack(ActivityInfo activityInfo, int battleType, List<Integer> patronsIdList, long enemyUserId, long enemyServerId,
                               String battleUid, int useItemId){
        UserTradeWarEnemyRecord userTradeWarSimpleRecord = crossEnemyRecordMap.get(enemyUserId);
        if (null == userTradeWarSimpleRecord) {
            return GameErrorCode.E_TRADE_WAR_NO_ATTACK_CANNOT_FIGHT_BACK;
        }
        if (userTradeWarSimpleRecord.getFightBackTimes() >= userTradeWarSimpleRecord.getTotalFightTimes()) {
            return GameErrorCode.E_TRADE_WAR_ALREADY_FIGHT_BACK;
        }
        UserTradeWarRecord tradeWarRecord = getCanFightBackCrossTradeWarRecord(enemyUserId);
        if (null == tradeWarRecord) {
            return GameErrorCode.E_TRADE_WAR_NO_ATTACK_CANNOT_FIGHT_BACK;
        }
        if (tradeWarRecord.isBattle()) {
            return GameErrorCode.E_TRADE_WAR_ALREADY_FIGHT_BACK;
        }
        if(enemyServerId == GameServer.getInstance().getServerId()) {//反击本服
            if(!TradeWarActivityMgr.canCrossTradeWar(activityInfo.getActivityId(), enemyUserId)){
                return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_CAN_NO_BATTLE;
            }
            UserTradeWarInfo enemyTradeWarInfo = TradeWarMgr.getUserTradeWarInfo(enemyUserId);
            UserInfo enemyUserInfo = UserMgr.getUserInfo(enemyUserId);
            if (null == enemyTradeWarInfo || null == enemyUserInfo) {
                return GameErrorCode.E_TRADE_WAR_BATTLE_ENEMY_NO_FOUND;
            }
            if (enemyUserId == player.getUserId()) {
                return GameErrorCode.E_TRADE_WAR_BATTLE_ENEMY_NO_SELF;
            }
            //判断门客的挑战次数
            CheckPatronsBattleResult checkResult = checkCrossBattleTimes(patronsIdList, false);
            if (0 != checkResult.getRet()) {
                return checkResult.getRet();
            }

            if (!GoodsMgr.isTradeWarChallenge(useItemId)) {
                return GameErrorCode.E_BAG_GOODS_NO_TRADE_WAR_CHALLENGE;
            }
            Property consume = new Property();
            consume.addProperty(useItemId, BigInteger.ONE);
            if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(useItemId, BigInteger.ONE),
                    eLogMoneyType.TradeWar, eLogMoneyType.CrossTradeWarChallenge)) {//判断挑战道具是否足够
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }

            //消耗次数
            checkResult = checkCrossBattleTimes(patronsIdList, true);
            if (0 != checkResult.getRet()) {
                return checkResult.getRet();
            }
            crossUserTradeWarBattle.setBattleType(battleType);
            setCrossPatronsList(patronsIdList);
            crossUserTradeWarBattle.setUseItemId(useItemId);
            setCrossBattleEnemyInfo(enemyUserId, enemyTradeWarInfo.getScore(), enemyUserInfo.getPatronsCount(),
                    UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()), battleUid);
            //设置反击
            tradeWarRecord.setBattle(true);
            userTradeWarSimpleRecord.setFightBackTimes(userTradeWarSimpleRecord.getFightBackTimes() + 1);
            syncCrossTradeWarEnemyRecord(userTradeWarSimpleRecord);
            AutoLogMgr.add(new LogTradeWarPrepare(player.getUserId(), battleType, enemyUserId, StringUtils.listToString(patronsIdList, ","),
                    PropertyHelper.parsePropertyToString(consume), true));
            //本地匹配完成，发送消息
            sendLocalPrepareFinish();
            return 0;
        }else {//挑战跨服
            if(!ServerListMgr.isServerProvideServices(enemyServerId)){//对手区服停服
                return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_SERVER_MAINTAIN;
            }
            //判断门客的挑战次数
            CheckPatronsBattleResult checkResult = checkCrossBattleTimes(patronsIdList, false);
            if (0 != checkResult.getRet()) {
                return checkResult.getRet();
            }
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(new Property(useItemId, BigInteger.ONE))) {//判断挑战道具是否足够
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            return sendCrossPrepare(activityInfo.getActivityId(), battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        }
    }

    /**
     * 跨服追缉
     * @param activityInfo
     * @param battleType
     * @param patronsIdList
     * @param enemyUserId
     * @param enemyServerId
     * @param battleUid
     * @param useItemId
     * @return
     */
    private int crossTrack(ActivityInfo activityInfo, int battleType, List<Integer> patronsIdList, long enemyUserId, long enemyServerId,
                           String battleUid, int useItemId){
        //判断门客的挑战次数
        if(eTradeWarBattleType.Track.getValue() != battleType) {//3.6修改追缉不消耗挑战次数
            CheckPatronsBattleResult checkResult = checkCrossBattleTimes(patronsIdList, false);
            if (0 != checkResult.getRet()) {
                return checkResult.getRet();
            }
        }
        //判断请求时间是否过快
        long nowTime = System.currentTimeMillis();
        if ((nowTime - lastTrackTime) < GameConfig.TRADE_WAR_WANTED_CD * 1000) {
            return GameErrorCode.E_TRADE_WAR_TRACK_TOO_FAST;
        }
        int ret = sendCrossPrepare(activityInfo.getActivityId(), battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
        if (ret == 0) {
            lastTrackTime = nowTime;
        }
        return ret;
    }

    /**
     * 发送到跨服
     */
    private int sendCrossPrepare(int activityId, int battleType, List<Integer> patronsIdList, long enemyUserId, long enemyServerId,
                                 String battleUid, int useItemId) {
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
        List<Long> serverList = new ArrayList<>();
        int groupId = UnionActivityGroupHelper.NO_GROUP_ID;
        if(null != activityInfo){
            groupId = GameUnionActivityGroupMgr.getGroupId(activityId, getUserId());
            UnionActivityGroup groupData = GameUnionActivityGroupMgr.getGroupData(activityId, groupId);
            for(long serverId : groupData.getServerSet()){
                if(GameServer.getInstance().getServerId() != serverId && ServerListMgr.isServerProvideServices(serverId)){
                    serverList.add(serverId);
                }
            }
        }
        if(serverList.size() < 1){
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_SERVER_MAINTAIN;
        }
        if(enemyServerId > 0 && !ServerListMgr.isServerProvideServices(enemyServerId)){
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_SERVER_MAINTAIN;
        }
        crossUserTradeWarBattle.setBattleType(battleType);
        setCrossPatronsList(patronsIdList);
        //发到跨服获取对手信息
        CrossTradeWarProto.CrossTradeWarBattleReqMsg.Builder reqMsg = CrossTradeWarProto.CrossTradeWarBattleReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        reqMsg.setBattleType(battleType);
        reqMsg.setEnemyUserId(enemyUserId);
        reqMsg.setEnemyServerId(enemyServerId);
        reqMsg.setBattleUid(battleUid);
        reqMsg.setUseItemId(useItemId);
        reqMsg.addAllPatronsIdList(patronsIdList);
        int dailyTrackTimes = 0;
        int limitTrackTimes = 0;
        if (battleType == eTradeWarBattleType.Track.getValue()) {
            dailyTrackTimes = userTradeWarInfo.getDailyTrackTimes();
            limitTrackTimes = ConfigMgr.getTradeWarTrackTimesByVip(VipMgr.getVipLv(player.getUserInfo().getVipExp()));
        }
        reqMsg.setDailyTrackTimes(dailyTrackTimes);
        reqMsg.setLimitTrackTimes(limitTrackTimes);
        reqMsg.setFastTeamNum(-1);
        reqMsg.setMyUnionId(player.getUserInfo().getUnionUid());
        GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_PREPARE,reqMsg,getUserId(),activityId,groupId);
        return 0;
    }

    private int sendCrossFastPrepare(int activityId, int battleType, List<Integer> patronsIdList, int teamNum) {
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
        List<Long> serverList = new ArrayList<>();
        int groupId = UnionActivityGroupHelper.NO_GROUP_ID;
        if (null != activityInfo) {
            groupId = GameUnionActivityGroupMgr.getGroupId(activityId, getUserId());
            UnionActivityGroup groupData = GameUnionActivityGroupMgr.getGroupData(activityId, groupId);
            for(long serverId : groupData.getServerSet()){
                if(GameServer.getInstance().getServerId() != serverId && ServerListMgr.isServerProvideServices(serverId)){
                    serverList.add(serverId);
                }
            }
        }
        if (serverList.size() < 1) {
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_SERVER_MAINTAIN;
        }
        crossUserTradeWarBattle.setBattleType(battleType);
        setCrossPatronsList(patronsIdList);
        //发到跨服获取对手信息
        CrossTradeWarProto.CrossTradeWarBattleReqMsg.Builder reqMsg = CrossTradeWarProto.CrossTradeWarBattleReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        reqMsg.setBattleType(battleType);
        reqMsg.addAllPatronsIdList(patronsIdList);
        reqMsg.setFastTeamNum(teamNum);
        reqMsg.setMyUnionId(player.getUserInfo().getUnionUid());
        GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_PREPARE,reqMsg,getUserId(),activityId,groupId);
        return 0;
    }

    /**
     * 商战战前鼓舞，买buff
     */
    public int buyBuff(int times) {
        if (null == userTradeWarInfo) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if (null == userTradeWarBattle) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if (userTradeWarBattle.getBuyBuffTimes() >= GameConfig.TRADE_WAR_BUFF_MAX_TIMES) {
            return GameErrorCode.E_TRADE_WAR_BUY_BUFF_TIMES_MAX;
        }
        for (int i = 0; i < times; i++) {
            BigInteger cost = TradeWarConfigMgr.getTradeWarBuffCost(player.getUserInfo().getEarnSpeed(),userTradeWarBattle.getBuyBuffTimes() + 1);
            if (cost.compareTo(BigInteger.ZERO) > 0) {
                if(userTradeWarBattle.getWarTimes() > 1){
                    cost = cost.multiply(BigInteger.valueOf(userTradeWarBattle.getWarTimes()));
                }
                if (player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_MONEY_SILVER, cost),
                        eLogMoneyType.TradeWar, eLogMoneyType.TradeWarBuyBuff)) {
                    userTradeWarBattle.setBuyBuffTimes(userTradeWarBattle.getBuyBuffTimes() + 1);
                    userTradeWarInfo.setTotalBuyBuffTimes(userTradeWarInfo.getTotalBuyBuffTimes() + userTradeWarBattle.getWarTimes());
                } else {
                    if(0 == i){
                        return GameErrorCode.E_BAG_SILVER_NO_ENOUGH;
                    }else {
                        break;
                    }
                }
            }else {
                break;
            }
            if(userTradeWarBattle.getBuyBuffTimes() >= GameConfig.TRADE_WAR_BUFF_MAX_TIMES){
                break;
            }
        }
        //成就、任务
        player.notifyListener(eGamePlayerEventType.TradeWarTotalBuyBuffTimes.getValue(), userTradeWarInfo);
        return 0;
    }

    /**
     * 跨服商战战前鼓舞，买buff
     */
    public int buyCrossBattleBuff(int activityId, int times) {
        if(null == userTradeWarInfo){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if(null == crossUserTradeWarBattle){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if(crossUserTradeWarBattle.getBuyBuffTimes() >= GameConfig.CROSS_TRADE_WAR_BUFF_MAX_TIMES){
            return GameErrorCode.E_TRADE_WAR_BUY_BUFF_TIMES_MAX;
        }
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if(null == activityInfo){
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if(crossUserTradeWarBattle.getActivityId() != activityId){//没参赛资格
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_QUALIFIED;
        }

        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, getUserId());
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_QUALIFIED;
        }

        if(!ActivityMgr.activityInTime(activityInfo)){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        for (int i = 0; i < times; i++) {
            BigInteger cost = TradeWarConfigMgr.getCrossTradeWarBuffCost(player.getUserInfo().getEarnSpeed(),crossUserTradeWarBattle.getBuyBuffTimes() + 1);
            if (cost.compareTo(BigInteger.ZERO) > 0) {
                if (player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_MONEY_SILVER, cost),
                        eLogMoneyType.TradeWar, eLogMoneyType.CrossTradeWarBuyBuff)) {
                    crossUserTradeWarBattle.setBuyBuffTimes(crossUserTradeWarBattle.getBuyBuffTimes() + 1);
                    userTradeWarInfo.setTotalBuyBuffTimes(userTradeWarInfo.getTotalBuyBuffTimes() + 1);
                } else {
                    if(0 == i){
                        return GameErrorCode.E_BAG_SILVER_NO_ENOUGH;
                    }else {
                        break;
                    }
                }
            }else {
                break;
            }
            if(crossUserTradeWarBattle.getBuyBuffTimes() >= GameConfig.CROSS_TRADE_WAR_BUFF_MAX_TIMES){
                break;
            }
        }
        //成就、任务
        player.notifyListener(eGamePlayerEventType.TradeWarTotalBuyBuffTimes.getValue(), userTradeWarInfo);
        return 0;
    }


    private BigInteger getAddPatronsEarnSpeed(List<UserPatrons> patronsList , int killPatronsCount, int useItemId){
        BigDecimal addEarnSpeed = BigDecimal.ZERO;
        if(GoodsMgr.isTradeWarChallenge(useItemId)){
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(useItemId);
            BigInteger param3 = goodsInfo.getParamList().get(2);
            //战斗干掉几个增加门客赚速
            TitleInfo titleInfo = TitleMgr.getTitleInfo(player.getTitleId());
            addEarnSpeed = BigDecimal.valueOf(titleInfo.getTraderWarEarnSpeed()).
                    multiply(BigDecimal.valueOf(killPatronsCount)).
                    multiply(new BigDecimal(param3)).
                    divide(BigDecimal.valueOf(1000),0,BigDecimal.ROUND_UP);
            for(UserPatrons userPatrons : patronsList){
                userPatrons.setTradeWarAddEarnSpeed(userPatrons.getTradeWarAddEarnSpeed().add(addEarnSpeed.toBigInteger()));
            }
            player.getModule(PatronsModule.class).syncPatronsData(patronsList,false);
            player.getModule(PatronsModule.class).onPatronsListChange(patronsList);
        }
        return addEarnSpeed.toBigInteger();
    }
    /**
     * 商战战斗开始
     */
    public BattleResult battleStart() {
        List<UserPatrons> enemyPatronsList = new ArrayList<>();
        //机器人
        if (-1 == userTradeWarBattle.getEnemyUserId()) {
            Map<Integer, UserPatrons> myPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
            if(null != myPatronsMap) {
                enemyPatronsList = TradeWarConfigMgr.initNpcPatronList(new ArrayList<>(myPatronsMap.values()));
            }
        } else {
            GamePlayer enemyPlayer = GamePlayerMgr.getOnlinePlayer(userTradeWarBattle.getEnemyUserId());
            if (null == enemyPlayer) {
                enemyPatronsList = EstateWarMgr.getEstateFloorPatronsList(userTradeWarBattle.getEnemyUserId());
                if(null == enemyPatronsList || enemyPatronsList.size() <= 0) {
                    enemyPatronsList = new ArrayList<>(UserPatronsBussiness.getUserPatronsMap(userTradeWarBattle.getEnemyUserId()).values());
                }
            } else {
                enemyPatronsList = new ArrayList<>(enemyPlayer.getModule(PatronsModule.class).getUserPatronsMap().values());
            }
            //对手没有门客，打机器人
            if (enemyPatronsList.size() == 0) {
                Map<Integer, UserPatrons> myPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
                if(null != myPatronsMap) {
                    enemyPatronsList = TradeWarConfigMgr.initNpcPatronList(new ArrayList<>(myPatronsMap.values()));
                }
            }
        }
        //打乱对面人才
        enemyPatronsList = TradeWarConfigMgr.disorganizeOrder(enemyPatronsList);

        //buff加成
        int buffAddition = TradeWarConfigMgr.getTradeWarBuffAddition(userTradeWarBattle.getBuyBuffTimes());
        List<UserPatrons> patronsList = player.getModule(PatronsModule.class).getUserPatronsList(userTradeWarBattle.getPatronsList());
        BattleResult battleResult = BattleManager.battle(player.getUserId(), patronsList, userTradeWarBattle.getEnemyUserId(),
                enemyPatronsList, buffAddition, true, false);

        TradeWarMgr.dealBattleResult(battleResult, userTradeWarBattle.getBattleType(), userTradeWarBattle.getUseItemId(),
                userTradeWarBattle.getWarTimes(), userTradeWarBattle.getBattleUid());

        BigInteger addEarnSpeed = getAddPatronsEarnSpeed(patronsList, battleResult.getKillPatronsCount(), userTradeWarBattle.getUseItemId());
        battleResult.setAddEarnSpeed(addEarnSpeed);

        long oldScore = userTradeWarInfo.getScore();
        changeScore(battleResult);

        // 增加公告信息
        if (battleResult.getKillPatronsCount() >= GameConfig.TRADE_WAR_NOTICE_NEED_KILL_PATRONS_COUNT) {
            addNotice(battleResult);
        }

        //发放奖励
        sendReward(battleResult, false);
        //增加记录
        addRecord(battleResult);


        if(eTradeWarBattleType.Challenge.getValue() == userTradeWarBattle.getBattleType() || eTradeWarBattleType.FightBack.getValue() == userTradeWarBattle.getBattleType()) {//挑战或者反击
            player.notifyListener(eGamePlayerEventType.TradeWarChallengeTimes.getValue(), 1);
        }
        AutoLogMgr.add(new LogTradeWarBattle(player.getUserId(), userTradeWarBattle.getBattleType(), userTradeWarBattle.getEnemyUserId(),
                StringUtils.listToString(userTradeWarBattle.getPatronsList(), ","),
                battleResult.getKillPatronsCount() * userTradeWarBattle.getWarTimes(), battleResult.getReward(), oldScore,
                battleResult.getMyAddScore(), userTradeWarInfo.getScore(), battleResult.getEnemyLoseScore(), addEarnSpeed.longValue()));
        //商战次数任务、成就
        notifyTradeWarTimes(userTradeWarBattle.getWarTimes());
        //清除战斗数据
        clearUserTradeWarBattle();

        List<BattleResult> battleResultList = new ArrayList<>();
        battleResultList.add(battleResult);
        DataAnalyticsMgr.trackOreWarBattle(player, battleResultList);
        return battleResult;
    }

    /**
     * 跨服商战战斗开始
     */
    public BattleResult crossBattleStart(int activityId) {
        if(crossUserTradeWarBattle.getBattleType() != eTradeWarBattleType.Track.getValue() && crossUserTradeWarBattle.getEnemyUserId() > 0 &&
                crossUserTradeWarBattle.getEnemyBaseInfo().getServerId() == GameServer.getInstance().getServerId()){//本服战斗
            List<UserPatrons> enemyPatronsList;
            GamePlayer enemyPlayer = GamePlayerMgr.getOnlinePlayer(crossUserTradeWarBattle.getEnemyUserId());
            if (null == enemyPlayer) {
                enemyPatronsList = EstateWarMgr.getEstateFloorPatronsList(crossUserTradeWarBattle.getEnemyUserId());
                if(null == enemyPatronsList) {
                    enemyPatronsList = new ArrayList<>(UserPatronsBussiness.getUserPatronsMap(crossUserTradeWarBattle.getEnemyUserId()).values());
                }
            } else {
                enemyPatronsList = new ArrayList<>(enemyPlayer.getModule(PatronsModule.class).getUserPatronsMap().values());
            }
            //打乱对面人才
            enemyPatronsList = TradeWarConfigMgr.disorganizeOrder(enemyPatronsList);

            //buff加成
            int buffAddition = TradeWarConfigMgr.getCrossTradeWarBuffAddition(crossUserTradeWarBattle.getBuyBuffTimes());
            List<UserPatrons> patronsList = player.getModule(PatronsModule.class).getUserPatronsList(crossUserTradeWarBattle.getPatronsList());
            BattleResult battleResult = BattleManager.battle(player.getUserId(), patronsList, crossUserTradeWarBattle.getEnemyUserId(),
                    enemyPatronsList, buffAddition, true, false);
            battleResult.setUseItemId(crossUserTradeWarBattle.getUseItemId());
            //战斗胜利增加门客赚速
            BigInteger addEarnSpeed = getAddPatronsEarnSpeed(patronsList, battleResult.getKillPatronsCount(), crossUserTradeWarBattle.getUseItemId());
            battleResult.setAddEarnSpeed(addEarnSpeed);

            for(UserPatrons userPatrons : patronsList){
                userPatrons.setTradeWarAddEarnSpeed(userPatrons.getTradeWarAddEarnSpeed().add(addEarnSpeed));
            }
            player.getModule(PatronsModule.class).syncPatronsData(patronsList,false);

            long oldScore = userTradeWarInfo.getCrossScore();
            changeCrossScore(battleResult, crossUserTradeWarBattle.getEnemyUserId());
            //发放奖励
            sendReward(battleResult, true);
            //增加记录
            TradeWarActivityMgr.addCrossRecord(activityId, crossUserTradeWarBattle.getBattleType(), userTradeWarInfo.getCrossScore(),
                    battleResult.getKillPatronsCount(), battleResult.getEnemyLoseScore(), crossUserTradeWarBattle.getEnemyUserId(),
                    player.getUserId(), UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId()));
            //增加跨服公告信息
            ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
            int serverCount = 1;
            if(null != activityInfo){
                serverCount = activityInfo.getServerIdList().size();
            }
            if (battleResult.getKillPatronsCount() >= ConfigMgr.getCrossTradeWarNoticeNeedKillPatronsCount(serverCount)) {
                addCrossNotice(activityId, battleResult);
            }

            if(eTradeWarBattleType.Challenge.getValue() == crossUserTradeWarBattle.getBattleType()) {//挑战
                player.notifyListener(eGamePlayerEventType.TradeWarChallengeTimes.getValue(), 1);
            }
//            LogMgr.addLogTradeWarBattle(player.getUserId(), crossUserTradeWarBattle.getBattleType(), crossUserTradeWarBattle.getEnemyUserId(),
//                    StringUtils.listToString(crossUserTradeWarBattle.getPatronsList(), ","), battleResult.getKillPatronsCount(), battleResult.getReward(), oldScore,
//                    battleResult.getMyAddScore(), userTradeWarInfo.getCrossScore(), battleResult.getEnemyLoseScore(),addEarnSpeed.longValue());

            battleResult.setTeamIndex(crossUserTradeWarBattle.getFastTeamNum());

            AutoLogMgr.add(new LogCrossTradeWarBattle(player.getUserId(), crossUserTradeWarBattle.getBattleType(), crossUserTradeWarBattle.getEnemyUserId(),
                    battleResult.getKillPatronsCount(), battleResult.getMyAddScore(), battleResult.getEnemyLoseScore(), battleResult.getReward(),
                    addEarnSpeed.longValue(), crossUserTradeWarBattle.getBuyBuffTimes()));
            //清除战斗数据
            clearCrossTradeWarBattle();
            //商战次数任务、成就
            notifyTradeWarTimes(1);

            return battleResult;
        }else {//发到跨服去拉取对手数据
            CrossTradeWarProto.CrossTradeWarToEnemyBattleReqMsg.Builder msg = CrossTradeWarProto.CrossTradeWarToEnemyBattleReqMsg.newBuilder();
            msg.setActivityId(activityId);
            msg.setMyUserId(player.getUserId());
            msg.setMyServerId(GameServer.getInstance().getServerId());
            msg.setEnemyUserId(crossUserTradeWarBattle.getEnemyUserId());
            msg.setEnemyServerId(crossUserTradeWarBattle.getEnemyBaseInfo().getServerId());
            msg.setUseItemId(crossUserTradeWarBattle.getUseItemId());
            msg.setBattleUid(crossUserTradeWarBattle.getBattleUid());
            msg.setBuyBuffTimes(crossUserTradeWarBattle.getBuyBuffTimes());
            msg.setBattleType(crossUserTradeWarBattle.getBattleType());
            msg.setAddScoreSkillAddition(TradeWarConfigMgr.getAddTradeWarScoreSkillAddition(player, crossUserTradeWarBattle.getPatronsList()));
            msg.setLoseScoreSkillAddition(TradeWarConfigMgr.getLoseTradeWarScoreSkillAddition(player, crossUserTradeWarBattle.getPatronsList()));
            msg.setMyScore(userTradeWarInfo.getCrossScore());
            msg.setRewardSkillAddition(TradeWarConfigMgr.getAddTradeWarScoreItemSkillAddition(player));
            msg.setMyBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
            List<UserPatrons> patronsList = player.getModule(PatronsModule.class).getUserPatronsList(crossUserTradeWarBattle.getPatronsList());
            for(UserPatrons userPatrons : patronsList) {
                PatronsProto.CrossPatronsTempMsg.Builder patronsMsg = PatronsPb.parseCrossPatronsTempMsg(userPatrons);
                if(null != patronsMsg) {
                    msg.addPatronsList(patronsMsg);
                }
            }
            msg.setFastTeamNum(crossUserTradeWarBattle.getFastTeamNum());
            player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_TO_ENEMY_BATTLE, msg, activityId);
            return null;
        }
    }

    /**
     * 处理跨服返回响应
     * @param battleMsg
     * @return
     */
    public BattleResult dealCrossBattleResp(CrossTradeWarProto.CrossTradeWarToEnemyBattleRespMsg battleMsg) {
        BattleResult battleResult = new BattleResult();
        battleResult.setBattleType(battleMsg.getBattleType());
        battleResult.setMyPatronsIdList(battleMsg.getPatronsIdListList());
        battleResult.setKillPatronsCount(battleMsg.getKillPatronsCount());
        battleResult.setMyAddScore(battleMsg.getMyAddScore());
        battleResult.setReward(battleMsg.getBattleReward());
        battleResult.setTrackChangeType(battleMsg.getTrackChangeType());
        battleResult.setUseItemId(crossUserTradeWarBattle.getUseItemId());
        battleResult.setWantedItemId(battleMsg.getWantedItemId());
        List<UserPatrons> patronsList = player.getModule(PatronsModule.class).getUserPatronsList(battleResult.getMyPatronsIdList());
        BigInteger addEarnSpeed = getAddPatronsEarnSpeed(patronsList, battleResult.getKillPatronsCount(), crossUserTradeWarBattle.getUseItemId());
        battleResult.setAddEarnSpeed(addEarnSpeed);

        TradeWarActivityMgr.changeCrossTradeWarScore(player.getUserId(), battleResult.getMyAddScore());
        notifyKillPatronsCount(battleResult.getKillPatronsCount(), battleResult.getWarTimes());

        //发放奖励
        if(battleResult.getBattleType() == eTradeWarBattleType.Track.getValue()) {
            sendCrossBattleReward(battleResult);
        }else {
            sendReward(battleResult, true);
        }

        if(eTradeWarBattleType.Challenge.getValue() == battleMsg.getBattleType()) {//挑战
            player.notifyListener(eGamePlayerEventType.TradeWarChallengeTimes.getValue(), 1);
        }
//        LogMgr.addLogTradeWarBattle(player.getUserId(), userTradeWarBattle.getBattleType(), userTradeWarBattle.getEnemyUserId(),
//                StringUtils.listToString(userTradeWarBattle.getPatronsList(), ","), battleResult.getKillPatronsCount(), battleResult.getReward(), oldScore,
//                battleResult.getMyAddScore(), userTradeWarInfo.getScore(), battleResult.getEnemyLoseScore(),addEarnSpeed.longValue());

        AutoLogMgr.add(new LogCrossTradeWarBattle(player.getUserId(), battleMsg.getBattleType(), crossUserTradeWarBattle.getEnemyUserId(),
                battleResult.getKillPatronsCount(), battleResult.getMyAddScore(), battleMsg.getEnemyLoseScore(), battleResult.getReward(),
                addEarnSpeed.longValue(), crossUserTradeWarBattle.getBuyBuffTimes()));

        //清除战斗数据
        clearCrossTradeWarBattle();
        //商战次数任务、成就
        notifyTradeWarTimes(1);
        battleResult.setTeamIndex(battleMsg.getFastTeamNum());
        return battleResult;
    }

    /**
     * 商战次数任务、成就
     * @param addTimes
     */
    public void notifyTradeWarTimes(int addTimes){
        //增加商战次数
        userTradeWarInfo.setTotalTradeWarTimes(userTradeWarInfo.getTotalTradeWarTimes() + addTimes);
        //成就、任务
        player.notifyListener(eGamePlayerEventType.TradeWarTimes.getValue(), addTimes);
        player.notifyListener(eGamePlayerEventType.TradeWarTotalTimes.getValue(), userTradeWarInfo);
    }

    private void notifyKillPatronsCount(int killPatronsCount, int warTimes){
        userTradeWarInfo.setTotalKillPatronsCount(userTradeWarInfo.getTotalKillPatronsCount() + killPatronsCount * warTimes);
        if(killPatronsCount > userTradeWarInfo.getMaxKillPatronsCount()){  //最大击杀数，既连胜
            userTradeWarInfo.setMaxKillPatronsCount(killPatronsCount);
        }

        player.notifyListener(eGamePlayerEventType.TradeWarKillPatronsCount.getValue(), killPatronsCount * warTimes);
        player.notifyListener(eGamePlayerEventType.UnionTradeWarKillPatronsCount.getValue(), new UnionActivityTaskArgs(UnionActivityTaskArgs.TYPE_ADD_VALUE, killPatronsCount * warTimes, player.getUserInfo().getUnionUid()));
        player.notifyListener(eGamePlayerEventType.TradeWarTotalKillPatronsCount.getValue(), userTradeWarInfo); //累计击杀数
        player.notifyListener(eGamePlayerEventType.TradeWarMaxKillPatronsCount.getValue(), userTradeWarInfo);   //连胜成就
        player.notifyListener(eGamePlayerEventType.UserTotalTreadWarkill.getValue(),killPatronsCount * warTimes);
        //平台数据加一下
        player.getModule(XiaoMianModule.class).addTradeWarKillPatronsCount(killPatronsCount);
    }

    /**
     * 计算门客随机战斗次数
     */
    public void calcRandomBattleTimes() {
        if(null != tradeWarPatronsDataMap){
            long nowTime = System.currentTimeMillis() / 1000;
            List<UserTradeWarPatronsData> syncList = new ArrayList<>();
            int maxRestoreBattleTimes = getMaxRestoreRandomBattleTimes(false);
            for(UserTradeWarPatronsData userTradeWarPatronsData : tradeWarPatronsDataMap.values()){
                if(userTradeWarPatronsData.getRandomBattleTimes() <= 0){
                    if(userTradeWarPatronsData.getRandomBattleRestoreTimes() < GameConfig.TRADE_WAR_PATRONS_RANDOM_BATTLE_MAX_RESTORE_TIMES){
                        if(nowTime - userTradeWarPatronsData.getRestoreRandomBattleTime() > GameConfig.TRADE_WAR_PATRONS_RESTORE_RANDOM_BATTLE_TIME){
                            userTradeWarPatronsData.setRandomBattleTimes(maxRestoreBattleTimes);
                            userTradeWarPatronsData.setRandomBattleRestoreTimes(userTradeWarPatronsData.getRandomBattleRestoreTimes() + 1);
                            syncList.add(userTradeWarPatronsData);
                        }
                    }
                }
            }
            if(syncList.size() > 0){
                syncUserTradeWarPatronsData(syncList);
            }
        }
    }

    /**
     * 门客是否有随机战斗次数
     */
    private boolean hasRandomBattleTimes(List<Integer> patronsIdList, int warTimes) {
        if(null == patronsIdList){
            return false;
        }
        for (int patronsId : patronsIdList) {
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                return false;
            }
            if(patronsData.getRandomBattleTimes() < warTimes){
                return false;
            }
        }
        return true;
    }

    /**
     * 计算跨服门客随机战斗次数
     */
    private void calcCrossRandomBattleTimes() {
        if(null != tradeWarPatronsDataMap){
            long nowTime = System.currentTimeMillis() / 1000;
            List<UserTradeWarPatronsData> syncList = new ArrayList<>();
            int maxRestoreBattleTimes = TradeWarConfigMgr.getMaxCrossRestoreRandomBattleTimes(false);
            for(UserTradeWarPatronsData userTradeWarPatronsData : tradeWarPatronsDataMap.values()){
                if(userTradeWarPatronsData.getCrossRandomBattleTimes() <= 0){
                    if(userTradeWarPatronsData.getCrossRandomBattleRestoreTimes() < GameConfig.CROSS_TRADE_WAR_PATRONS_RANDOM_BATTLE_MAX_RESTORE_TIMES){
                        if(nowTime - userTradeWarPatronsData.getCrossRestoreRandomBattleTime() > GameConfig.CROSS_TRADE_WAR_PATRONS_RESTORE_RANDOM_BATTLE_TIME){
                            userTradeWarPatronsData.setCrossRandomBattleTimes(maxRestoreBattleTimes);
                            userTradeWarPatronsData.setCrossRandomBattleRestoreTimes(userTradeWarPatronsData.getCrossRandomBattleRestoreTimes() + 1);
                            syncList.add(userTradeWarPatronsData);
                        }
                    }
                }
            }
            if(syncList.size() > 0){
                syncCrossUserTradeWarPatronsData(syncList);
            }
        }
    }

    /**
     * 门客是否有跨服随机战斗次数
     */
    private boolean hasCrossRandomBattleTimes(List<Integer> patronsIdList) {
        if(null == patronsIdList){
            return false;
        }
        if (patronsIdList.isEmpty()){
            return false;
        }
        for (int patronsId : patronsIdList) {
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                return false;
            }
            if(patronsData.getCrossRandomBattleTimes() < 1){
                return false;
            }
        }
        return true;
    }

    /**
     * 增加跨服公告
     * @param activityId
     * @param battleResult
     */
    private void addCrossNotice(int activityId, BattleResult battleResult) {
        UserInfo enemyUserInfo = UserMgr.getUserInfo(crossUserTradeWarBattle.getEnemyUserId());
        UserInfo userInfo = UserMgr.getUserInfo(player.getUserId());
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, getUserId());
        CrossTradeWarNotice data = new CrossTradeWarNotice();
        data.setActivityId(activityId);
        data.setUserId(userInfo.getUserId());
        data.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
        data.setBattleType(crossUserTradeWarBattle.getBattleType());
        data.setAllKill(battleResult.getKillPatronsCount() >= crossUserTradeWarBattle.getEnemyPatronsCount());
        data.setKillPatronsCount(battleResult.getKillPatronsCount());
        data.setNoticeTime(System.currentTimeMillis() / 1000);
        data.setEnemyUserId(crossUserTradeWarBattle.getEnemyUserId());
        data.setEnemyBaseInfo(UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()));
        List<CrossTradeWarNotice> syncList = new ArrayList<>();
        syncList.add(data);
        CrossTradeWarProto.CrossTradeWarNoticeListSyncMsg.Builder syncMsg = CrossTradeWarProto.CrossTradeWarNoticeListSyncMsg.newBuilder();
        CrossTradeWarProto.CrossTradeWarNoticeListMsg.Builder listMsg = CrossTradeWarPb.parseCrossTradeWarNoticeListMsg(syncList);
        syncMsg.setGroupId(groupId);
        syncMsg.setActivityId(activityId);
        syncMsg.setDataList(listMsg);

        player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_ADD_NOTICE, syncMsg, activityId);
    }

    public void addNotice(BattleResult battleResult) {
        if(battleResult.getEnemyUserId() > 0) {
            UserInfo enemyUserInfo = UserMgr.getUserInfo(battleResult.getEnemyUserId());
            UserInfo userInfo = UserMgr.getUserInfo(player.getUserId());

            TradeWarNotice notice = initTradeWarNotice(battleResult, enemyUserInfo, userInfo);
            TradeWarMgr.addTradeWarNotice(notice);
        }
    }

    private TradeWarNotice initTradeWarNotice(BattleResult battleResult, UserInfo enemyUserInfo, UserInfo userInfo) {
        TradeWarNotice tradeWarNotice = new TradeWarNotice();
        tradeWarNotice.setUserId(userInfo.getUserId());
        tradeWarNotice.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
        tradeWarNotice.setBattleType(battleResult.getBattleType());
        tradeWarNotice.setAllKill(battleResult.getKillPatronsCount() >= battleResult.getEnemyPatronsList().size());
        tradeWarNotice.setKillPatronsCount(battleResult.getKillPatronsCount());
        tradeWarNotice.setNoticeTime(System.currentTimeMillis() / 1000);
        tradeWarNotice.setEnemyUserId(enemyUserInfo.getUserId());
        tradeWarNotice.setEnemyBaseInfo(UserMgr.parseUserBaseInfo(enemyUserInfo, GameServer.getInstance().getServerId()));
        return tradeWarNotice;
    }

    public void addRecord(BattleResult battleResult) {
        if (battleResult.getEnemyUserId() > 0) {
            UserInfo userInfo = player.getUserInfo();
            long score = 0;
            if(null != userTradeWarInfo){
                score = userTradeWarInfo.getScore();
            }

            long nowTime = System.currentTimeMillis() / 1000;
            UserTradeWarRecord record = new UserTradeWarRecord();
            record.setUserId(battleResult.getEnemyUserId());
            record.setRecordUid(UUIDHelper.randomUUID(String.valueOf(GameServer.getInstance().getServerId())));
            record.setBattleType(battleResult.getBattleType());
            record.setEnemyUserId(userInfo.getUserId());
            record.setEnemyBaseData(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
            record.setEnemyScore(score);
            record.setKillPatronsCount(battleResult.getKillPatronsCount());
            record.setLoseScore(battleResult.getEnemyLoseScore());
            record.setRecordTime(nowTime);
            record.setBattle(false);
            record.setInsertOption();

            TradeWarMgr.addTradeRecordTask(record);

            //如果是追辑，产生追辑记录
            if(eTradeWarBattleType.Track.getValue() == battleResult.getBattleType()) {
                TradeWarMgr.trackRecord(player, battleResult.getBattleUid(), battleResult);
            }
        }
    }

    /**
     * 变更跨服分数
     * @param battleResult
     * @param enemyUserId
     */
    private void changeCrossScore(BattleResult battleResult, long enemyUserId) {
        //使用道具加成效果
        GoodsInfo goodsInfo = null;
        if(crossUserTradeWarBattle.getUseItemId() > 0) {
            goodsInfo = GoodsMgr.getGoodsById(crossUserTradeWarBattle.getUseItemId());
        }
        int addScore = battleResult.getKillPatronsCount() * 2;
//        log.info("userId:{},trade war my add score:{}", player.getUserId(), addScore);
        if(null != goodsInfo){
            addScore = addScore * goodsInfo.getParamList().get(0).intValue();
//            log.info("userId:{},trade war use item my add score:{}", player.getUserId(), addScore);
        }
        int addScoreSkillAddition = TradeWarConfigMgr.getAddTradeWarScoreSkillAddition(player, battleResult.getMyPatronsIdList());
        BigDecimal val1 = BigDecimal.valueOf(addScoreSkillAddition + 1000).divide(BigDecimal.valueOf(1000), CalculationManager.CALCULATION_SCALE,
                BigDecimal.ROUND_UP);
        BigDecimal val2 = val1.multiply(BigDecimal.valueOf(addScore));
        addScore = val2.setScale(0, BigDecimal.ROUND_UP).toBigInteger().intValue();
//        log.info("userId:{},trade war addition my add score:{}, addScoreSkillAddition:{}", player.getUserId(), addScore, addScoreSkillAddition);
        battleResult.setMyAddScore(addScore);
        TradeWarActivityMgr.changeCrossTradeWarScore(player.getUserId(), addScore);
        // 扣除对面积分
        if (battleResult.getKillPatronsCount() > 0) {
            int loseScore = battleResult.getKillPatronsCount();
//            log.info("userId:{},trade war enemy lose score:{}", player.getUserId(), loseScore);
            if(null != goodsInfo){
                loseScore = loseScore * goodsInfo.getParamList().get(1).intValue();
//                log.info("userId:{},trade war use item enemy lose score:{}", player.getUserId(), loseScore);
            }
            int loseScoreSkillAddition = TradeWarConfigMgr.getLoseTradeWarScoreSkillAddition(player, battleResult.getMyPatronsIdList());
            long loseScoreSkillReduce = TradeWarConfigMgr.getLoseTradeWarScoreSkillReduce(battleResult.getEnemyPatronsList());
            long skillAddition = Math.max(1000 + loseScoreSkillAddition + loseScoreSkillReduce, 0);
            BigDecimal val3 = BigDecimal.valueOf(skillAddition).divide(BigDecimal.valueOf(1000), CalculationManager.CALCULATION_SCALE,
                    BigDecimal.ROUND_UP);
            BigDecimal val4 = val3.multiply(BigDecimal.valueOf(loseScore));
            loseScore = val4.setScale(0, BigDecimal.ROUND_UP).toBigInteger().intValue();
//            log.info("userId:{},trade war addition enemy lose score:{}, patronsAddition:{}", player.getUserId(), loseScore, patronsSkillAddition);
            battleResult.setEnemyLoseScore(loseScore);
            if(enemyUserId > 0) {
                addScore = 0 - battleResult.getEnemyLoseScore();
                TradeWarActivityMgr.changeCrossTradeWarScore(enemyUserId, addScore);
                //被击杀任务、成就
                TradeWarMgr.notifyEnemyBeKillPatronsCount(enemyUserId, battleResult.getKillPatronsCount());
            }
        }
        //击杀任务、成就
        notifyKillPatronsCount(battleResult.getKillPatronsCount(), battleResult.getWarTimes());
    }

    /**
     * 根据战斗结果变更分数
     * @param battleResult
     */
    public void changeScore(BattleResult battleResult) {
        //使用道具加成效果
        GoodsInfo goodsInfo = null;
        if(battleResult.getUseItemId() > 0) {
            goodsInfo = GoodsMgr.getGoodsById(battleResult.getUseItemId());
        }
        int addScore = battleResult.getKillPatronsCount() * 2;
//        log.info("userId:{},trade war my add score:{}", player.getUserId(), addScore);
        if(null != goodsInfo){
            addScore = addScore * goodsInfo.getParamList().get(0).intValue();
//            log.info("userId:{},trade war use item my add score:{}", player.getUserId(), addScore);
        }
        if(battleResult.getBattleType() == eTradeWarBattleType.Track.getValue()){//追辑分数翻倍
            GoodsInfo wantedGoods = GoodsMgr.getGoodsById(battleResult.getWantedItemId());
            if(null != wantedGoods){
                int param2 = wantedGoods.getParamList().get(1).intValue();
                addScore = addScore * param2;
            }
//            log.info("userId:{},trade war my track add score:{}", player.getUserId(), addScore);
        }
        int addScoreSkillAddition = TradeWarConfigMgr.getAddTradeWarScoreSkillAddition(player, battleResult.getMyPatronsIdList());
        BigDecimal val1 = BigDecimal.valueOf(1000 + addScoreSkillAddition).divide(BigDecimal.valueOf(1000), CalculationManager.CALCULATION_SCALE,
                BigDecimal.ROUND_UP);
        BigDecimal val2 = val1.multiply(BigDecimal.valueOf(addScore));
        addScore = val2.setScale(0, BigDecimal.ROUND_UP).toBigInteger().intValue();
//        addScore = (int) Math.ceil((addScoreSkillAddition / 1000 + 1) * addScore);
//        log.info("userId:{},trade war addition my add score:{}, addScoreSkillAddition:{}", player.getUserId(), addScore, addScoreSkillAddition);
        addScore = addScore * battleResult.getWarTimes();
        battleResult.setMyAddScore(addScore);
        TradeWarMgr.changeTradeWarScore(player.getUserId(), addScore);

        // 扣除对面积分 如果是追击并且追击人数已经满了就不扣对方积分
        if (battleResult.getKillPatronsCount() > 0 && !isTrackFullAfterAddRecord(battleResult.getBattleType(), battleResult.getBattleUid())) {   //按需求，对方扣除积分不加倍
            int loseScore = battleResult.getKillPatronsCount();
//            log.info("userId:{},trade war enemy lose score:{}", player.getUserId(), loseScore);
            if(null != goodsInfo){
                loseScore = loseScore * goodsInfo.getParamList().get(1).intValue();
//                log.info("userId:{},trade war use item enemy lose score:{}", player.getUserId(), loseScore);
            }
            int loseScoreSkillAddition = TradeWarConfigMgr.getLoseTradeWarScoreSkillAddition(player, battleResult.getMyPatronsIdList());
            long loseScoreSkillReduce = TradeWarConfigMgr.getLoseTradeWarScoreSkillReduce(battleResult.getEnemyPatronsList());
            long skillAddition = Math.max(1000 + loseScoreSkillAddition + loseScoreSkillReduce, 0);
            BigDecimal val3 = BigDecimal.valueOf(skillAddition).divide(BigDecimal.valueOf(1000), CalculationManager.CALCULATION_SCALE,
                    BigDecimal.ROUND_UP);
            BigDecimal val4 = val3.multiply(BigDecimal.valueOf(loseScore));
            loseScore = val4.setScale(0, BigDecimal.ROUND_UP).toBigInteger().intValue();
//            log.info("userId:{},trade war addition enemy lose score:{}, patronsAddition:{}", player.getUserId(), loseScore, patronsSkillAddition);
            battleResult.setEnemyLoseScore(loseScore);
            if(battleResult.getEnemyUserId() > 0) {
                addScore = 0 - battleResult.getEnemyLoseScore();
                TradeWarMgr.changeTradeWarScoreTask(battleResult.getEnemyUserId(), addScore);
                //被击杀任务、成就
                TradeWarMgr.notifyEnemyBeKillPatronsCount(battleResult.getEnemyUserId(), battleResult.getKillPatronsCount() * battleResult.getWarTimes());
            }
        }
        //击杀任务、成就
        notifyKillPatronsCount(battleResult.getKillPatronsCount(), battleResult.getWarTimes());
    }

    /**
     * 添加追击记录之后是否已满(添加前判断 预留1个记录位置)
     * @return
     */
    public boolean isTrackFullAfterAddRecord(int battleType, String battleUid) {
        if (eTradeWarBattleType.Track.getValue() == battleType) {
            TradeWarWanted tradeWarWanted = TradeWarMgr.getTradeWarWanted(battleUid);
            if (tradeWarWanted == null) {
                return true;
            }
            long publishUserId = tradeWarWanted.getUserId();
            if (player.getUserId() == publishUserId) {
                if (TradeWarMgr.isPublishUserTrackFull(battleUid)) {
                    return true;
                }
            } else {
                if (TradeWarMgr.isHelpUserTrackFull(battleUid)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 发送商战奖励
     * @param battleResult
     */
    public void sendReward(BattleResult battleResult, boolean isCrossTradeWar) {
        Property reward = new Property();
        //添加钱庄经验
        int bankExp;
        //商战币奖励
        long tradeWarScore;
        //添加通缉奖励
        if(!isCrossTradeWar) {//本服
            bankExp = TradeWarConfigMgr.getBankExpReward(battleResult.getKillPatronsCount(), battleResult.getUseItemId());
            //税引直接翻倍，不按击杀门客数翻倍后随机值
            if(battleResult.getWarTimes() > 1){ //随机值后加倍
                bankExp = bankExp * battleResult.getWarTimes();
            }
            tradeWarScore = TradeWarConfigMgr.getTradeWarScoreReward(player, battleResult.getKillPatronsCount(), battleResult.getUseItemId());
            if (battleResult.getBattleType() == eTradeWarBattleType.Track.getValue()) {
                TradeWarWanted tradeWarWanted = TradeWarMgr.getTradeWarWanted(battleResult.getBattleUid());
                if (null == tradeWarWanted) {
                    tradeWarWanted = TradeWarMgr.getFinishTradeWarWanted(battleResult.getBattleUid());
                }
                if ((!TradeWarMgr.isWantedTime(tradeWarWanted))) {//通缉过期了
                    battleResult.setBattleType(eTradeWarBattleType.RandomBattle.getValue());
                } else {//通缉奖励，并且翻倍奖励
                    Property wantedReward = PropertyHelper.parseStringToProperty(tradeWarWanted.getReward());
                    reward.addProperty(wantedReward);
                    GoodsInfo wantedGoods = GoodsMgr.getGoodsById(battleResult.getWantedItemId());
                    if(null != wantedGoods){
                        int param2 = wantedGoods.getParamList().get(1).intValue();
                        tradeWarScore = param2 * tradeWarScore;
                    }
                    log.info("userId:{},trade war sendReward wanted score:{}", player.getUserId(), tradeWarScore);
                }
            }
            MammonEffectResult effectResult = player.getModule(MammonModule.class).isMammonSkillEffect(eSkillType.MammonTradeWarScoreAddition.getValue(), tradeWarScore);
            if(effectResult.getEffectMammonSkill() > 0){
                long oldTradeWarScore = tradeWarScore;
                tradeWarScore = effectResult.getValue();  //
                if(battleResult.getWarTimes() > 1){
                    //其他次数加倍，没有神迹加成
                    tradeWarScore = tradeWarScore + (battleResult.getWarTimes() - 1) * oldTradeWarScore;
                }
                log.info("userId:{},trade war sendReward mammon skill score:{}", player.getUserId(), tradeWarScore);
            }else {// 无神迹加成，直接多倍
                if(battleResult.getWarTimes() > 1){
                    tradeWarScore = tradeWarScore * battleResult.getWarTimes();
                }
            }
            battleResult.setEffectMammonSkill(effectResult.getEffectMammonSkill());
        }else {
            bankExp = TradeWarConfigMgr.getCrossBankExpReward(battleResult.getKillPatronsCount(), crossUserTradeWarBattle.getUseItemId());
            tradeWarScore = TradeWarConfigMgr.getCrossTradeWarScoreReward(player, battleResult.getKillPatronsCount(),
                    crossUserTradeWarBattle.getUseItemId());
        }
        reward.addProperty(GameConfig.GAME_ITEM_TRADE_WAR_TAX_OFFICE, BigInteger.valueOf(bankExp));
        if(isCrossTradeWar){//加名誉币
            reward.addProperty(GameConfig.GAME_MONEY_CROSS_TRADE_WAR_SCORE, BigInteger.valueOf(tradeWarScore));
            userTradeWarInfo.setCrossTradeWarMoney(userTradeWarInfo.getCrossTradeWarMoney() + tradeWarScore);  //增加名誉币累计值
            syncUserTradeWarInfo();
        }else {//加商战币
            reward.addProperty(GameConfig.GAME_MONEY_TRADE_WAR_SCORE, BigInteger.valueOf(tradeWarScore));
        }
        if(isCrossTradeWar) {
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.TradeWar, eLogMoneyType.CrossTradeWarBattle);
        }else {
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.TradeWar, eLogMoneyType.TradeWarBattle);
        }
        battleResult.setReward(PropertyHelper.parsePropertyToString(reward));
    }

    private void setBattleEnemyInfo(long enemyUserId, String enemyNickName, int enemyTitleId, String enemyDecoration, long enemyScore,
                                    long enemyVipExp, int enemyPatronsCount, String enemyCity) {
        userTradeWarBattle.setEnemyUserId(enemyUserId);
        userTradeWarBattle.setEnemyNickName(enemyNickName);
        userTradeWarBattle.setEnemyTitleId(enemyTitleId);
        userTradeWarBattle.setEnemyDecoration(enemyDecoration);
        userTradeWarBattle.setEnemyScore(enemyScore);
        userTradeWarBattle.setEnemyVipExp(enemyVipExp);
        userTradeWarBattle.setEnemyPatronsCount(enemyPatronsCount);
        userTradeWarBattle.setEnemyCity(enemyCity);
        userTradeWarBattle.setModifyTime(System.currentTimeMillis() / 1000);
    }

    public void addRecord(UserTradeWarRecord record) {
        synchronized (recordList) {
            recordList.addFirst(record);
            if(TradeWarConfigMgr.isTodayEnemyRecord(record)) {//不是反击，进行来犯记录
                addEnemyRecord(record);
            }
        }
    }

    private void addEnemyRecord(UserTradeWarRecord record) {
        UserTradeWarEnemyRecord enemyRecord = enemyRecordMap.get(record.getEnemyUserId());
        if (null == enemyRecord) {
            enemyRecord = new UserTradeWarEnemyRecord();
            enemyRecord.setUserId(player.getUserId());
            enemyRecord.setEnemyUserId(record.getEnemyUserId());
            enemyRecord.setEnemyBaseInfo(record.getEnemyBaseData());
            enemyRecord.setEnemyScore(record.getEnemyScore());
            enemyRecord.setTotalFightTimes(0);
            enemyRecord.setFightBackTimes(0);
            enemyRecordMap.put(enemyRecord.getEnemyUserId(), enemyRecord);
        }
        enemyRecord.setEnemyBaseInfo(record.getEnemyBaseData());
        enemyRecord.setTotalFightTimes(enemyRecord.getTotalFightTimes() + 1);
        if(record.isBattle()){
            enemyRecord.setFightBackTimes(enemyRecord.getFightBackTimes() + 1);
        }
    }

    /**
     * 增加跨服商战记录
     */
    public void addCrossRecord(UserTradeWarRecord record) {
        synchronized (crossTradeWarRecordList) {
            crossTradeWarRecordList.addLast(record);
            if(TradeWarConfigMgr.isTodayEnemyRecord(record)){
                addCrossEnemyRecord(record, true);
            }
        }
        syncCrossTradeRecord(record);
    }

    /**
     * 增加对手记录
     * @param record
     */
    private void addCrossEnemyRecord(UserTradeWarRecord record, boolean isSendMsg) {
        UserTradeWarEnemyRecord enemyRecord = crossEnemyRecordMap.get(record.getEnemyUserId());
        if (null == enemyRecord) {
            enemyRecord = new UserTradeWarEnemyRecord();
            enemyRecord.setUserId(player.getUserId());
            enemyRecord.setEnemyUserId(record.getEnemyUserId());
            enemyRecord.setEnemyBaseInfo(record.getEnemyBaseData());
            enemyRecord.setEnemyScore(record.getEnemyScore());
            enemyRecord.setTotalFightTimes(0);
            enemyRecord.setFightBackTimes(0);
            crossEnemyRecordMap.put(enemyRecord.getEnemyUserId(), enemyRecord);
        }
        enemyRecord.setEnemyBaseInfo(record.getEnemyBaseData());
        enemyRecord.setTotalFightTimes(enemyRecord.getTotalFightTimes() + 1);
        if(record.isBattle()){
            enemyRecord.setFightBackTimes(enemyRecord.getFightBackTimes() + 1);
        }
        if(isSendMsg){//发送同步数据
            syncCrossTradeWarEnemyRecord(enemyRecord);
        }
    }

    private UserTradeWarRecord getCanFightBackTradeWarRecord(long enemyUserId) {
        for (UserTradeWarRecord record : getRecordList()) {
            if (record.getEnemyUserId() == enemyUserId && !record.isBattle() &&
                    TradeWarConfigMgr.isTodayEnemyRecord(record)) {
                return record;
            }
        }
        return null;
    }

    /**
     * 获取一个今日能够反击的记录
     */
    private UserTradeWarRecord getCanFightBackCrossTradeWarRecord(long enemyUserId) {
        for (UserTradeWarRecord record : getCrossRecordList()) {
            if (record.getEnemyUserId() == enemyUserId && !record.isBattle() &&
                    TradeWarConfigMgr.isTodayEnemyRecord(record)) {
                return record;
            }
        }
        return null;
    }

    /**
     * 挑战次数校验
     */
    private CheckPatronsBattleResult checkBattleTimes(List<Integer> patronsIdList, boolean isCost) {
        int ingots = 0;         //消耗元宝数
        CheckPatronsBattleResult checkResult = new CheckPatronsBattleResult();
        List<Integer> needBuyTimesPatronsId = new ArrayList<>();
        for (int patronsId : patronsIdList) {
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                checkResult.setRet(GameErrorCode.E_PATRONS_NO_FOUND);
                return checkResult;
            }

            if (patronsData.getBattleTimes() >= GameConfig.TRADE_WAR_PATRONS_DEFAULT_BATTLE_TIMES) {
                if(patronsData.getBattleTimes() >= TradeWarConfigMgr.getPatronsMaxBattleTimes()){
                    //超过挑战次数了
                    checkResult.setRet(GameErrorCode.E_TRADE_WAR_BATTLE_TIMES_OVER);
                    return checkResult;
                }else {
                    needBuyTimesPatronsId.add(patronsId);
                    ingots += TradeWarConfigMgr.getPatronsBuyBattleTimesCost(patronsData.getBuyBattleTimes());
                }
            }
        }
        if(isCost) {
            long nowTime = System.currentTimeMillis() / 1000;
            List<UserTradeWarPatronsData> syncList = new ArrayList<>();
            Property consume = new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(ingots));
            if (!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.TradeWar, eLogMoneyType.TradeWarBuyBattleTimes)) {//元宝不足
                checkResult.setRet(GameErrorCode.E_BAG_INGOTS_NO_ENOUGH);
                return checkResult;
            }
            checkResult.setConsume(consume);
            for (int patronsId : patronsIdList) {
                UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
                patronsData.setBattleTimes(patronsData.getBattleTimes() + 1);
                patronsData.setModifyTime(nowTime);
                syncList.add(patronsData);
            }
            for (int patronsId : needBuyTimesPatronsId) {
                UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
                patronsData.setBuyBattleTimes(patronsData.getBuyBattleTimes() + 1);
                patronsData.setModifyTime(nowTime);
            }
            syncUserTradeWarPatronsData(syncList);
            //增加累计挑战次数
            userTradeWarInfo.setTotalChallengeTimes(userTradeWarInfo.getTotalChallengeTimes() + 1);
            //成就、任务
            player.notifyListener(eGamePlayerEventType.TradeWarTotalChallengeTimes.getValue(), userTradeWarInfo);
        }else {
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(ingots)))) {//元宝不足
                checkResult.setRet(GameErrorCode.E_BAG_INGOTS_NO_ENOUGH);
                return checkResult;
            }
        }
        return checkResult;
    }

    /**
     * 跨服挑战次数校验
     */
    private CheckPatronsBattleResult checkCrossBattleTimes(List<Integer> patronsIdList, boolean isCost) {
        CheckPatronsBattleResult checkResult = new CheckPatronsBattleResult();
        for (int patronsId : patronsIdList) {
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                checkResult.setRet(GameErrorCode.E_PATRONS_NO_FOUND);
                return checkResult;
            }

            if (patronsData.getCrossBattleTimes() >= TradeWarConfigMgr.getCrossPatronsMaxBattleTimes()) {
                //超过挑战次数了
                checkResult.setRet(GameErrorCode.E_TRADE_WAR_BATTLE_TIMES_OVER);
                return checkResult;
            }
        }
        if(isCost) {
            long nowTime = System.currentTimeMillis() / 1000;
            List<UserTradeWarPatronsData> syncList = new ArrayList<>();
            for (int patronsId : patronsIdList) {
                UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
                patronsData.setCrossBattleTimes(patronsData.getCrossBattleTimes() + 1);
                patronsData.setModifyTime(nowTime);
                syncList.add(patronsData);
            }
            syncCrossUserTradeWarPatronsData(syncList);
            //增加累计挑战次数
            userTradeWarInfo.setTotalChallengeTimes(userTradeWarInfo.getTotalChallengeTimes() + 1);
            //成就、任务
            player.notifyListener(eGamePlayerEventType.TradeWarTotalChallengeTimes.getValue(), userTradeWarInfo);
        }
        return checkResult;
    }

    /**
     * 扣除门客随机出战次数
     */
    private void reduceRandomBattleTimes(List<Integer> patronsIdList, int reduceTimes) {
        long nowTime = System.currentTimeMillis() / 1000;
        List<UserTradeWarPatronsData> syncList = new ArrayList<>();
        for(int patronsId : patronsIdList){
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                continue;
            }
            int randomBattleTimes = patronsData.getRandomBattleTimes() - reduceTimes;
            if(randomBattleTimes < 0){
                randomBattleTimes = 0;
            }
            patronsData.setRandomBattleTimes(randomBattleTimes);
            patronsData.setTotalRandomBattleTimes(patronsData.getTotalRandomBattleTimes() + reduceTimes);
            patronsData.setModifyTime(nowTime);
            if(patronsData.getRandomBattleTimes() <= 0){
                patronsData.setRestoreRandomBattleTime(nowTime);
            }
            syncList.add(patronsData);
        }
        syncUserTradeWarPatronsData(syncList);
    }

    /**
     * 扣除门客跨服随机出战次数
     */
    private void reduceCrossRandomBattleTimes(List<Integer> patronsIdList) {
        long nowTime = System.currentTimeMillis() / 1000;
        List<UserTradeWarPatronsData> syncList = new ArrayList<>();
        for(int patronsId : patronsIdList){
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                continue;
            }
            int crossRandomBattleTimes = patronsData.getCrossRandomBattleTimes() - 1;
            if(crossRandomBattleTimes < 0){
                crossRandomBattleTimes = 0;
            }
            patronsData.setCrossRandomBattleTimes(crossRandomBattleTimes);
            patronsData.setCrossTotalRandomBattleTimes(patronsData.getCrossTotalRandomBattleTimes() + 1);
            patronsData.setModifyTime(nowTime);
            if(patronsData.getCrossRandomBattleTimes() <= 0){
                patronsData.setCrossRestoreRandomBattleTime(nowTime);
            }
            syncList.add(patronsData);
        }
        syncCrossUserTradeWarPatronsData(syncList);
    }

    public void notifyAddPatrons(UserPatrons userPatrons){
        if(SystemOpenMgr.systemOpen(player, eSystemId.TradeWar.getValue())) {
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(userPatrons.getPatronsId());
            if (null != patronsData) {
                syncUserTradeWarPatronsData(patronsData);
                if(TradeWarActivityMgr.canCrossTradeWar(player.getUserId())){
                    syncCrossUserTradeWarPatronsData(patronsData);
                }
            }
        }
    }

    private void setPatronsList(List<Integer> patronsIdList) {
        if(null != userTradeWarBattle) {
            userTradeWarBattle.setPatronsList(new ArrayList<>());
            for (int patronsId : patronsIdList) {
                userTradeWarBattle.addPatronsList(patronsId);
            }
        }
    }

    private void setCrossPatronsList(List<Integer> patronsIdList) {
        if(null != crossUserTradeWarBattle) {
            crossUserTradeWarBattle.setPatronsList(new ArrayList<>());
            for (int patronsId : patronsIdList) {
                crossUserTradeWarBattle.addPatronsList(patronsId);
            }
        }
    }

    /**
     * 商战恢复出战的次数
     */
    private int getMaxRestoreRandomBattleTimes(boolean isDefault){
        if(isDefault){
            return GameConfig.TRADE_WAR_PATRONS_DEFAULT_RANDOM_BATTLE_TIMES + player.getModule(CardModule.class).tradeWarRandomBattleAddRestoreTimes();
        }else {
            return GameConfig.TRADE_WAR_PATRONS_RESTORE_RANDOM_BATTLE_TIMES + player.getModule(CardModule.class).tradeWarRandomBattleAddRestoreTimes();
        }
    }

    public List<UserTradeWarRecord> getRecordList() {
        LinkedList<UserTradeWarRecord> tempRecordList;
        synchronized (recordList) {
            tempRecordList = new LinkedList<>(recordList);
        }
        return tempRecordList;
    }

    /**
     * 获取跨服商战的记录
     */
    public List<UserTradeWarRecord> getCrossRecordList() {
        LinkedList<UserTradeWarRecord> tempRecordList;
        synchronized (crossTradeWarRecordList) {
            tempRecordList = new LinkedList<>(crossTradeWarRecordList);
        }
        return tempRecordList;
    }

    public List<UserTradeWarRecord> getTopRecordList() {
        LinkedList<UserTradeWarRecord> tempRecordList;
        synchronized (recordList) {
            tempRecordList = new LinkedList<>(recordList);
        }
        if(tempRecordList.size() > GameConfig.TRADE_WAR_MAX_RECORD){
            tempRecordList.subList(0, GameConfig.TRADE_WAR_MAX_RECORD);
        }
        return tempRecordList;
    }

    public List<UserTradeWarEnemyRecord> getUserTradeWarEnemyRecordList(){
        return new ArrayList<>(enemyRecordMap.values());
    }

    /**
     * 获取跨服商战对手列表
     */
    public List<UserTradeWarEnemyRecord> getCrossTradeWarEnemyRecordList(){
        return new ArrayList<>(crossEnemyRecordMap.values());
    }

    public UserTradeWarInfo getUserTradeWarInfo() {
        return userTradeWarInfo;
    }

    public CrossUserTradeWarBattle getCrossUserTradeWarBattle() {
        return crossUserTradeWarBattle;
    }

    public void syncCrossTradeRecord(UserTradeWarRecord userTradeWarRecord) {
        if(null != userTradeWarRecord){
            List<UserTradeWarRecord> syncList = new ArrayList<>();
            syncList.add(userTradeWarRecord);
            syncCrossTradeRecord(syncList, false);
        }
    }

    private void syncCrossTradeRecord(List<UserTradeWarRecord> dataList, boolean isLogin){
        if(isLogin){
            player.sendPacket(Protocol.U_CROSS_TRADE_WAR_RECORD_LIST, TradeWarPb.parseTradeWarRecordListMsg(dataList));
        }else {
            player.sendPacket(Protocol.U_CROSS_TRADE_WAR_RECORD_SYNC, TradeWarPb.parseTradeWarRecordListMsg(dataList));
        }
    }

    private void syncCrossTradeWarEnemyRecord(UserTradeWarEnemyRecord userTradeWarEnemyRecord){
        if(null != userTradeWarEnemyRecord) {
            List<UserTradeWarEnemyRecord> syncList = new ArrayList<>();
            syncList.add(userTradeWarEnemyRecord);
            syncCrossTradeWarEnemyRecord(syncList, false);
        }
    }

    private void syncCrossTradeWarEnemyRecord(List<UserTradeWarEnemyRecord> recordList, boolean isLogin){
        if(isLogin) {
            player.sendPacket(Protocol.U_CROSS_TRADE_WAR_ENEMY_RECORD_LIST, TradeWarPb.parseTradeWarEnemyRecordListMsg(recordList));
        }else {
            player.sendPacket(Protocol.U_CROSS_TRADE_WAR_ENEMY_RECORD_SYNC, TradeWarPb.parseTradeWarEnemyRecordListMsg(recordList));
        }
    }

    /**
     * 获取当前跨服商战名誉币累计值
     */
    public long getCrossTradeWarMoney(){
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
        if(null != userTradeWarInfo && null != activityInfo){
            if(userTradeWarInfo.getActivityId() == activityInfo.getActivityId()){
                return userTradeWarInfo.getCrossTradeWarMoney();
            }
        }
        return 0;
    }

    /**
     * 扣除队伍门客随机出战次数
     */
    public ReduceTeamRandomBattleTimesResult reduceTeamRandomBattleTimes(List<Integer> patronsIdList) {
        ReduceTeamRandomBattleTimesResult result = new ReduceTeamRandomBattleTimesResult();
        List<Integer> tempList = new ArrayList<>();
        int battleTimes = GameConfig.TRADE_WAR_PATRONS_RESTORE_RANDOM_BATTLE_TIMES;
        for(int patronsId : patronsIdList){
            UserTradeWarPatronsData patronsData = getUserTradeWarPatronsData(patronsId);
            if(null == patronsData){
                continue;
            }
            if(patronsData.getRandomBattleTimes() > 0){
                tempList.add(patronsId);
                if(patronsData.getRandomBattleTimes() < battleTimes){
                    battleTimes = patronsData.getRandomBattleTimes();
                }
            }
        }
        if(tempList.size() > 0){
            result.setBattleTimes(battleTimes);
            result.setPatronsList(tempList);
            reduceRandomBattleTimes(tempList, battleTimes);
        }
        return result;
    }

    /**
     * 发布商战通缉
     * @param activityId
     * @param wantedUserId
     * @param wantedServerId
     * @return
     */
    public int publishCrossTradeWarWanted(int activityId, long wantedUserId, long wantedServerId, int useItemId){
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if(null == activityInfo){
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if(crossUserTradeWarBattle.getActivityId() != activityId){//没参赛资格
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_QUALIFIED;
        }
        if(!ActivityMgr.activityInTime(activityInfo)){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        if(player.getUserId() == wantedUserId && wantedServerId == GameServer.getInstance().getServerId()){
            return GameErrorCode.E_TRADE_WAR_CAN_NO_WANTED_SELF;
        }
        if(null == userTradeWarInfo){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if(!GoodsMgr.isTradeWarWanted(useItemId)){
            return GameErrorCode.E_TRADE_WAR_NO_WANTED_GOODS;
        }
        Property consume = new Property(useItemId, BigInteger.ONE);
        if(!player.getModule(CurrencyModule.class).currencyIsEnough(consume)){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }

        if (GameUnionActivityGroupMgr.getGroupId(activityId,getUserId())!=GameUnionActivityGroupMgr.getGroupId(activityId,wantedUserId)){
            return GameErrorCode.E_UNION_ACTIVITY_NO_SAME_GROUP;
        }
        //预扣除消耗
        player.getModule(PreReduceModule.class).preReduce(PropertyHelper.parsePropertyToString(consume));
        //发送到跨服
        CrossTradeWarProto.CrossTradeWarPublishWantedToCrossReqMsg.Builder reqMsg = CrossTradeWarProto.CrossTradeWarPublishWantedToCrossReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        reqMsg.setUserId(player.getUserId());
        reqMsg.setUserBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
        reqMsg.setWantedUserId(wantedUserId);
        reqMsg.setWantedServerId(wantedServerId);
        reqMsg.setUseItemId(useItemId);

        player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_PUBLISH_WANTED, reqMsg, activityId);
        return 0;
    }

    /**
     * 发布跨服通缉响应
     * @param activityId
     * @param tradeWarWanted
     * @return
     */
    public int publishCrossTradeWarWantedResponse(int activityId, TradeWarWanted tradeWarWanted, Property consume, boolean isAddRecord){
        //累计发布通缉次数
        userTradeWarInfo.setTotalPublishWantedTimes(userTradeWarInfo.getTotalPublishWantedTimes() + 1);
        //成就、任务
        player.notifyListener(eGamePlayerEventType.PublishWantedTotalTimes.getValue(), userTradeWarInfo);
        LogMgr.addLogPublishWanted(player.getUserId(), tradeWarWanted.getWantedUserId(), PropertyHelper.parsePropertyToString(consume),
                tradeWarWanted.getWantedTime());
        //同步通缉记录
        syncCrossTradeWarWantedRecord(tradeWarWanted);
        //聊天窗口发布通缉消息
//        WorldMessageMgr.worldNotify(player, eMessageType.TradeWarWanted.getValue(), tradeWarWanted.getWantedBaseInfo().getNickName());
        //被通缉处理
        TradeWarActivityMgr.dealBeCrossWanted(tradeWarWanted);
        //全服通知
        TradeWarActivityMgr.worldNotifyCrossWanted(tradeWarWanted);
        return 0;
    }

    /**
     * 发送跨服获取通缉列表、通缉记录
     */
    public void sendCrossGetWantedList(int activityId){
        CrossTradeWarProto.CrossTradeWarWantedListReqMsg.Builder reqMsg = CrossTradeWarProto.CrossTradeWarWantedListReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_WANTED_LIST, reqMsg, activityId);
    }

    /**
     * 发送跨服战斗奖励
     * @param battleResult
     */
    public void sendCrossBattleReward(BattleResult battleResult) {
        Property reward = PropertyHelper.parseStringToProperty(battleResult.getReward());
        if(null == reward){
            reward = new Property();
        }
        if(!TradeWarConfigMgr.isCrossTrackChange(battleResult.getTrackChangeType())){
            Property wantedReward = PropertyHelper.parseStringToProperty(GameConfig.TRADE_WAR_WANTED_REWARD);
            GoodsInfo wantedGoods = GoodsMgr.getGoodsById(battleResult.getWantedItemId());
            if(null != wantedGoods){
                int param1 = wantedGoods.getParamList().get(0).intValue();
                wantedReward.rideProperty(param1);
            }
            reward.addProperty(wantedReward);  //通缉奖励
            battleResult.setReward(PropertyHelper.parsePropertyToString(reward));
        }
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.TradeWar, eLogMoneyType.CrossTradeWarBattle);
        //增加名誉币累计值
        long tradeWarScore = reward.getCountByGoodsId(GameConfig.GAME_MONEY_CROSS_TRADE_WAR_SCORE).longValue();
        userTradeWarInfo.setCrossTradeWarMoney(userTradeWarInfo.getCrossTradeWarMoney() + tradeWarScore);
        syncUserTradeWarInfo();
    }

    /**
     * 发布商战通缉
     * @param activityId
     * @param wantedUserId
     * @param wantedServerId
     * @return
     */
    public int crossTradeWarCanWanted(int activityId, long wantedUserId, long wantedServerId){
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if(null == activityInfo){
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if(crossUserTradeWarBattle.getActivityId() != activityId){//没参赛资格
            return GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_QUALIFIED;
        }
        if(!ActivityMgr.activityInTime(activityInfo)){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        if(player.getUserId() == wantedUserId && wantedServerId == GameServer.getInstance().getServerId()){
            return GameErrorCode.E_TRADE_WAR_CAN_NO_WANTED_SELF;
        }
        if(null == userTradeWarInfo){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        //发送到跨服
        CrossTradeWarProto.CrossTradeWarQueryWantedReqMsg.Builder reqMsg = CrossTradeWarProto.CrossTradeWarQueryWantedReqMsg.newBuilder();
        reqMsg.setActivityId(activityId);
        reqMsg.setWantedUserId(wantedUserId);
        reqMsg.setWantedServerId(wantedServerId);
        player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_QUERY_CAN_WANTED, reqMsg, activityId);
        return 0;
    }

    private void syncCrossTradeWarWantedRecord(TradeWarWanted tradeWarWanted){
        CrossTradeWarWantedRecord wantedRecord = new CrossTradeWarWantedRecord();
        wantedRecord.setActivityId(tradeWarWanted.getActivityId());
        wantedRecord.setUserId(tradeWarWanted.getUserId());
        wantedRecord.setServerId(tradeWarWanted.getUserBaseInfo().getServerId());
        wantedRecord.setWantedUserId(tradeWarWanted.getWantedUserId());
        wantedRecord.setWantedServerId(tradeWarWanted.getWantedBaseInfo().getServerId());
        wantedRecord.setWantedTime(tradeWarWanted.getWantedTime());
        List<CrossTradeWarWantedRecord> syncList = new ArrayList<>();
        syncList.add(wantedRecord);
        player.sendPacket(Protocol.U_CROSS_TRADE_WAR_WANTED_RECORD_SYNC, CrossTradeWarPb.parseCrossTradeWarWantedRecordListMsg(syncList));
    }


    public void addTraceTimes(int addTimes) {
        synchronized (userTradeWarInfo){
            userTradeWarInfo.setDailyTrackTimes(userTradeWarInfo.getDailyTrackTimes() + addTimes);
        }
        syncUserTradeWarInfo();
    }

    public int getTradeWarActivityJoinUnion(int activityId,int groupId){

        UnionActivityGroup groupData = GameUnionActivityGroupMgr.getGroupData(activityId, groupId);
        if (groupData == null){
            return GameErrorCode.E_UNION_ACTIVITY_GROUP_WAIT_GROUP;
        }
        CrossTradeWarProto.CanCrossTradeWarUnionNameResp.Builder builder = CrossTradeWarProto.CanCrossTradeWarUnionNameResp.newBuilder();
        builder.setRet(0);
        for (UnionActivityGroupUnion unionData: groupData.getUnionDataMap().values()){
            builder.addUnionName(unionData.getUnionBaseInfo().getUnionName());
        }
        player.sendPacket(ClientProtocol.U_CROSS_TRADE_WAR_JOIN_UNION_LIST, builder);
        return 0;
    }
}
